Table of Contents

‚Äč

How To Run A Command Multiple Times in a Loop in Bash

There are several ways to run a command multiple times in a loop in Bash:

for loop

In [4]:

for i in {1..5}; do
    echo $i
done

1
2
3
4
5

while loop

In [3]:

counter=1
while [ $counter -le 5 ]; do
  echo $counter
  ((counter++))
done

1
2
3
4
5

You can also use a command like seq in place of the range {1..5} to specify a different range of numbers or a variable to specify the number of iterations.

In [6]:

for i in $(seq 1 5); do
  echo $i
done

1
2
3
4
5

You can also use the for loop with in keyword to loop through an array of items

In [7]:

arr=(item1 item2 item3)
for i in "${arr[@]}"
do
  echo $i
done

item1
item2
item3

until loop

In [5]:

counter=1
until [ $counter -gt 5 ]; do
  echo $counter
  ((counter++))
done

1
2
3
4
5

Related Posts

1