3

Usually to run an infinite bash loop, I do something like the following:

while true; do
    echo test
    sleep 1
done

What if instead, I want to do a loop that loops infinitely as long as it is earlier than 20:00. Is there a way to do this in bash?

4

3 回答 3

6

You can use date to print the hours and then compare to the one you are looking for:

while [ $(date "+%H") -lt 20 ]; do
    echo "test"
    sleep 1
done

as date "+%H" shows the current hour, it keeps checking if we are already there or in a "smaller" hour.

于 2013-07-09T12:27:32.823 回答
4

If you want a specific date, not only full hours, then try comparing the Unix time:

while [ $(date +%s) -lt $(date --date="2016-11-04T20:00:00" +%s) ]; do
    echo test
    sleep 1
done
于 2016-11-04T20:04:38.923 回答
2

Just change true to the real condition:

while (( $(date +%H) < 20 )) ; do
    echo Still not 8pm.
    sleep 1
done
于 2013-07-09T12:27:28.387 回答