Linux / UNIX: Run Command a Number of Times In a Row

Linux / UNIX: Run Command a Number of Times In a Row

To run a command a number of times in a row in Linux or Unix, you can use a loop in a shell script.

There are several types of loops that you can use, such as for, while, and until. Here are some examples of how to use these loops to run a command a number of times:

  1. Use a for loop:
ref‮:ot re‬lautturi.com
#!/bin/sh

# Set the number of times to run the command
num_times=5

# Run the command in a for loop
for i in $(seq 1 $num_times)
do
  command
done

This script will run the command 5 times (assuming num_times is set to 5).

  1. Use a while loop:
#!/bin/sh

# Set the number of times to run the command
num_times=5

# Set a counter
counter=0

# Run the command in a while loop
while [ $counter -lt $num_times ]
do
  command
  counter=$((counter+1))
done

This script will also run the command 5 times.

  1. Use an until loop:
#!/bin/sh

# Set the number of times to run the command
num_times=5

# Set a counter
counter=0

# Run the command in an until loop
until [ $counter -ge $num_times ]
do
  command
  counter=$((counter+1))
done

This script will also run the command 5 times.

Keep in mind that these are just a few examples of how to run a command a number of times in a shell script. You can use a loop to run a command as many times as you need, and you can use different looping constructs depending on your specific requirements.

Created Time:2017-10-16 14:38:52  Author:lautturi