To execute a script on the next full minute I want to tell the sleep command to sleep until the next full minute. How can I do this?
2 Answers
Ask for the date in seconds: date +%s and calculate the reminder of the devision with 60 (modulo: %). If you calculate 60 minus the modulo you get the remaining seconds to the next full minute. You could change this to wait until the next full hour (change 60 to 3600).
sleep $((60 - $(date +%s) % 60)) &&
<yourscript>
To just sleep until the next full minute you can even make it shorter (without the modulo):
sleep $((60 - $(date +%S) )) &&
<yourscript>
Also be aware of this question and answer: sleep until next occurence of specific time.
-
5This computation is overkill, since `date` provides not only "seconds since epoch" but also plain "seconds". So `sleep $((60 - $(date +%S) ))` suffices. – Janis Apr 06 '15 at 19:22
-
good to know that it always can be done shorter, I will edit it. But for every other timespan you will need seconds since epoch, right? – nnn Apr 07 '15 at 05:46
-
For a hypothetical other question than the one asked, yes. But be aware that `date`'s format specifier `%s` (lower case) is also non-standard. – Janis Apr 07 '15 at 11:21
sleep $(( 60 - 10#$(date +%S) )) sleeps until the next full minute. Don't forget the 10# prefix! Otherwise your code will interpret "08" and "09" as invalid references to an octal number.
Or you can prevent the date command from padding the seconds with '0' by following the '%' with '-'
sleep $(( 60 - $(date +%-S) ))
- 51
- 2