Alex Reynolds
Alex Reynolds

Reputation: 96937

Sleeping within nested for loops in bash

I have a pair of nested for loops in a bash shell script.

I want to pause the script every 60 seconds when a counter hits a multiple of 50 "ticks" or iterations, so I put in a modulo test:

counter=1
for ((i=0; i<${#libraries[@]}; i++)); do
    for ((j=(i+1); j<${#libraries[@]}; j++)); do
        # do stuff...
        if [ $counter%50 == 0 ]; then
            sleep 60s
        fi
        counter=$[$counter+1]
    done
done

This loop behaves erratically — specifically, this script does not pause every 50 iterations, but occasionally staggers and mostly skips or otherwise does not appear to be triggering the expected sleep call correctly.

Whatever I put into # do stuff... this script does not pause as expected, but behaves in roughly the same erratic way. I can comment it out — same behavior.

The ${#libraries[@]} stuff is just an array of file paths.

Does sleep not work inside loops, or am I not using it correctly? Is there an alternative way to pause the script without breaking out the nested loops into separate wrapper scripts?

Upvotes: 1

Views: 615

Answers (1)

Fred
Fred

Reputation: 6995

I think your test is wrong. Try this instead :

if (( counter % 50 == 0 ))

The $counter%50 part will never expand to 0, so this test will always fail, and the sleep will never be executed. The % modulo operator requires an arithmetic context, which the standard test command does not provide, but the double parentheses will.

Upvotes: 1

Related Questions