Home

How to run bash commands in a loop

Introduction

Linux distros come with with a myriad of great command line utilities. This post brings a few snippets to help you run your utilities indefinitely, a fixed number of times, or until failure.

Running commands indefinitely

Two handy ways to run a command indefinitely are while loops and the watch command:

while loop
# Print date indefinitely at a half second interval

while true; do
  date
  sleep 0.5
done

Equivalent using the watch command:

watch indefinitely
# Print date indefinitely at a half second interval

watch -n 0.5 date

Both above are infinite loops. They can be stopped with Ctrl + C.

Running commands a fixed number of times

If you know ahead of time how many times you wish to run commands, a for loop is more appropriate:

for loop
# Print the iteration number every second

for ((n=0;n<5;n++))
do
  echo $(n)
  sleep 1
done

Running commands until failure

Exiting while loop:

exiting while loop
# Exit while loop when your-command returns something other than 0

while your-command; do
  sleep 0.5
done

Exiting watch:

exiting watch
# Exit watch when your-command returns something other than 0

watch -e -n 2 your-command

Exiting for loop:

exiting for loop
# Exit for loop when your-command returns something other than 0

for ((n=0;n<5;n++))
do
  if ! your-command; then
      break;
  fi
  sleep 1
done

Other cool flags with the watch command

There are two specially cool flags for the watch command:

  1. The -p or --precise flag allows us to ignore the length of the task, running the your-command at precise intervals.
  2. The -d or --differences flag allows us to highlight differences between the current output and previous output.
cool watch flags
watch -d -p -n 0.1 ntptime