user788171
user788171

Reputation: 17553

How to have a bash script loop until a specific time

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?

Upvotes: 4

Views: 14423

Answers (3)

mxmlnkn
mxmlnkn

Reputation: 2131

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

Upvotes: 6

fedorqui
fedorqui

Reputation: 289745

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.

Upvotes: 8

choroba
choroba

Reputation: 241898

Just change true to the real condition:

while (( $(date +%H) < 20 )) ; do
    echo Still not 8pm.
    sleep 1
done

Upvotes: 2

Related Questions