Skip to content

Instantly share code, notes, and snippets.

@stevekm
Last active March 23, 2017 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevekm/c56efe4cd0ddceb6706db7582e5ba7a6 to your computer and use it in GitHub Desktop.
Save stevekm/c56efe4cd0ddceb6706db7582e5ba7a6 to your computer and use it in GitHub Desktop.
bash for loop with sleep counter

After every third item, sleep [source]

counter=0
limit=3

foo="thing1 thing2 thing34 thing4 thing5 thing6 thing7 thing8 thing9 thing9"
for thing in $foo; do
    ( # start a subshell
    # increment the counter, sleep & reset it if its over the limit
    (( counter++ ))
    (( $counter > $limit )) && sleep 3 && counter=0
    echo "$thing"
    # do a lot more things
    ) & # send process to background
done

This is useful if you want to run many simultaneous processes by pushing each loop iteration into the background, but want to pause every n iterations so as not to flood the system too badly with processes.

Also you can use sleep $[ ( $RANDOM % 20 ) + 1 ]s for a random sleep timer (up to 20s).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment