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
doneEquivalent using the watch command:
watch indefinitely
# Print date indefinitely at a half second interval
watch -n 0.5 dateBoth 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
doneRunning 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
doneExiting watch:
exiting watch
# Exit watch when your-command returns something other than 0
watch -e -n 2 your-commandExiting 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
doneOther cool flags with the watch command
There are two specially cool flags for the watch command:
- The
-por--preciseflag allows us to ignore the length of the task, running the your-command at precise intervals. - The
-dor--differencesflag allows us to highlight differences between the current output and previous output.
cool watch flags
watch -d -p -n 0.1 ntptime