hithesh
hithesh

Reputation: 439

bash run commands for a period of time

I am trying to using system time in bash to run a few commands.
Here's a simplified version that I tried

echo $(date +%s); while [ $(($(date +%s)+10)) -gt $(date +%s) ]; do echo $(date +%s); done

I add 10secs to current time and print the time inside the while loop.
What I see is the program runs for more than 10secs and I have to hit ctrl+C to stop.

Upvotes: 0

Views: 350

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You check if the current time + 10 seconds is greater than the current time in your loop. That will always be true. It's the same as doing while (( (X+10) > X ))

You could instead calculate the endtime before starting the loop and use that in your comparison:

starttime=$(date +%s)
(( endtime = starttime + 10 ))

echo "$starttime - $endtime"

while (( endtime > $(date +%s) )); do
    date +%s
done

Upvotes: 4

Related Questions