Skip to content

Different methods to run a command in a loop in Linux

There are several ways to run a command in a loop in Linux. Some of these with simple examples are listed below. This can prove handy for some DBAs who need to perform simple operation in repetitive way.

for loop:
You can use the for loop to execute a command a specified number of times.
The basic syntax is:

for i in {1..N}; 
do command; 
done

For example, to run the date command 10 times:

for i in {1..10}; 
do date; 
done

while loop:
You can use the while loop to execute a command until a certain condition is met.
The basic syntax is:

while [ condition ]; 
do command; 
done

For example, to run the free -m command every 5 seconds:

while true; 
do free -m; 
sleep 5; 
done

 

until loop:
You can use the until loop to execute a command until a certain condition is met.
The basic syntax is:

until [ condition ]; 
do command; 
done

 

For example, to run the df -h command until the available disk space is less than 10%

until [[ $(df -h | awk '{print $5}' | grep -v Use | sed 's/%//g') -lt 10 ]]; 
do df -h; 
sleep 5; 
done

 

watch command:
You can use the watch command to run a command repeatedly and display the output on the screen.
The basic syntax is:

watch -n interval command

For example, to run the top command every 2 seconds:

watch -n 2 top

 

cron:

You can use cron to schedule a command to run at a specific time or interval.
The basic syntax is:

* * * * * command
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday = both 0 and 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

For example, to run the df -h command every 30 minutes

*/30 * * * * df -h >> /var/log/df.log

Depending on the task at hand, one of the above methods can be more suitable than the others.

Brijesh Gogia
Leave a Reply