It's sometimes useful to pause until a specified time (but inconvenient to use at
or the like), so I wrote a tiny script to wait until a user-specified time point is reached.
I use this when I want to keep the output of preceding and subsequent commands together, but I don't mind blocking the current terminal. Quite often, this would be M-xcompile
when I want to wait until after new source code/data have been uploaded, but still have the results in a compilation-mode buffer.
Although it's a very short script, my time at Code Review has taught me that almost any program has something that can be improved, so please make your suggestions!
#!/bin/sh
# Sleep until the specified time
# Accepts any date/time format accepted by 'date'
# Assumes GNU date and GNU sleep
die() {
echo "$@" >&2
exit 1
}
usage() {
echo "Usage: $0 TIME"
}
test $# = 1 || die $(usage)
case "$1" in
--version)
echo "sleep_until version 1.0"
exit 0
;;
--help)
usage
exit 0
;;
-*)
die "Unrecognised option: $1"
;;
*)
end=$(date -d "$1" +%s.%N)
now=$(date +%s.%N)
test ${end%.*} -gt ${now%.*} || die "$1 is in the past!"
exec sleep $(echo $end $now - p | dc )
;;
esac
Notes:
- We need GNU
date
for its-d
option and a good range of input formats. - GNU
sleep
handles fractional seconds; we could remove.%N
from the date formats to work with traditional/POSIXsleep
. - I've used
dc
for the arithmetic so we can use plainsh
rather than requiring a more heavyweight shell.