5

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?

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

2

Just change true to the real condition:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.