OSETC TECH

How to Use For Loop in Bash Shell

This post will guide you how to make a for loop in bash shell. How do I make a loop to repeat n times in Bash shell.

For Loop in Bash Shell


You can make a loop through a list, and the statements between do and done are performed once for every item in the list.
For example,

for num in 1 2 3 4 5 6
do
    echo $num
done

If you execute this script, it outputs like this:

devops@devops-osetc:~$ for num in 1 2 3 4 5 6
> do
> echo $num
> done
1
2
3
4
5
6

This for loop is executed under the command line interface, and if you want to put it in a shell script, you should add a hashbang, #!/bin/bash, it indicates which interpreter is going to be parse this script. Like this:

#!/bin/bash
for num in 1 2 3 4 5 6; do
    echo $num
done

Note:

for : it indicates that this is loop and it will iterate multiple times.
num: it is a variable,
in: it is a keyword, and it indicates that it is a separator between the variable num and the list of items to run over.
do …done: it indicates that the code should be repeated in this loop.

Iterating the current directory using For Loop


If you want to iterate the current directory or a given directory using for loop, you can write down the following loop script:

#!/bin/bash
for file in *
do
echo $file
done

Outputs:

devops@devops-osetc:~/working$ ./loop.sh
fio
fio3
fio.c
loop.sh
test.rar

For Loop Range in Bash


You can also use brackets to generate a range to make a for loop.

#!/bin/bash
for num in {1..6}
do
echo $num
done

Or you can also increase the step by which each integer increments. and it is +1 by default. if you want to set step as 2, like the below script:

#!/bin/bash
for num in {1..6..2}
do
echo $num
done

Outputs:

devops@devops-osetc:~/working$ ./loop.sh
1
3
5