Two handy ways to run a command indefinitely are
while loops and the
# Print date indefinitely at a half second interval while true; do date sleep 0.5 done
Equivalent using the
# 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.
If you know ahead of time how many times you wish to run commands, a
for loop is more appropriate:
# Print the iteration number every second for ((n=0;n<5;n++)) do echo $(n) sleep 1 done
# Exit while loop when your-command returns something other than 0 while your-command; do sleep 0.5 done
# Exit watch when your-command returns something other than 0 watch -e -n 2 your-command
# 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
There are two specially cool flags for the
--preciseflag allows us to ignore the length of the task, running the your-command at precise intervals.
--differencesflag allows us to highlight differences between the current output and previous output.
watch -d -p -n 0.1 ntptime