daxterss
daxterss

Reputation: 63

How to loop over a certain time?

I am creating a script that should wait until a certain file (e.g. stop.dat) appears or after certain time (e.g. 500 Seconds) has passed.

I know how to wait until the file appears:

while [ ! -f ./stop.dat ]; do
  sleep 30
done

How can I add the other statement in my while loop?

Upvotes: 5

Views: 49

Answers (2)

vv01f
vv01f

Reputation: 372

you could memorize the time and compare with current time in the loop condition

echo -n "before: "
date
t1=$(( $(date +"%s" ) + 15 )) #15 for testing or … your 500s later
    while [ $(date +"%s") -lt $t1  ] #add other condition with -a inside the [ ] which is shortcut for `test` command, in case you want to use `man`
    do
        sleep 3 #do stuff
    done
echo -n "after: "
date

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60163

If you want to do it this way, then you can do something like:

nap=30; slept=0
while [ ! -f ./stop.dat ] && ((slept<500)); do 
    sleep $nap; 
    slept=$((slept+nap))
done

Using inotifywait instead of polling would be a more proper way of doing it.

Upvotes: 2

Related Questions