Bash Script – Sleep Until Specific Time

bashdatesleeptime

I need a series of commands or a single command that sleeps until the next occurrence of a specific time like "4:00" occurs.

How would I do that?

The at command or a cronjob is not a option because I must not leave the script I'm currently in.

The specific case I am talking about is a script running in screen. It is very important that I do not stop the execution of the script by the script itself because there are store many important variables which are needed at some point of the script.
The script is not always supposed to be executed in a regular matter. It just needs to be executed at a specific time.

It would be very benificial if the script would have to create any files or any other tasks such as cronjobs or other screens. This is simply a question of design.

I just had an awsome idea:

difference=$(($(date -d "4:00" +%s) - $(date +%s)))

if [ $difference -lt 0 ]
then
    sleep $((86400 + difference))
else
    sleep $difference
fi

Do you have any better ideas?

More information will be added if requested!

Best Answer

terdon's suggestion would work but I guess mine is more efficient.

difference=$(($(date -d "4:00" +%s) - $(date +%s)))

if [ $difference -lt 0 ]
then
    sleep $((86400 + difference))
else
    sleep $difference
fi

This is calculating the difference between the given time and the current time in seconds. If the number is negative we have to add the seconds for a whole day (86400 to be exact) to get the seconds we have to sleep and if the number is postive we can just use it.

Related Question