Bash for loop

Bash for loop enables you to iterate through a list of values. In each iteration, you will get one of the values present in the list.

Bash for loop syntax

for variable in element1 element2 element3 ... elementN
do
   commands
done

Example: How to read values from a list using for loop?

for version in Pie Oreo Nougat Marshmallow Lollipop
do
   echo "Android version: $version"
done

Output of the above program

Pie
Oreo
Nougat
Marshmallow
Lollipop

Example: To print a table using Bash for loop

read -p "Enter a number to print its table: " number
for i in {1..10}
do
  echo "$number x $i = $((number*i))"
done

Output of the above program

Enter a number to print its table: 2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

How to read values from a command using Bash for loop?

Use backtick character to execute the command and feed its output to for loop. For example, we have created a file named android-version.txt in which we have mentioned different versions of Android OS. So we will use cat command to display its content and feed its output to for loop.

#cat android-version.txt
Pie
Oreo
Nougat
Marshmallow
Lollipop
Kitkat
Jelly Bean
for version in `cat android-version.txt`
do
   echo $version
done

Output of the above program

Pie
Oreo
Nougat
Marshmallow
Lollipop
Kitkat
Jelly
Bean

As you can see in the above output that Jelly Bean is split into two lines. To mitigate this problem, we have to use IFS environment variable. To learn more about IFS, visit Bash IFS.

How to iterate through directory using Bash for loop?

With the help of wildcard character, you can loop through a directory. For this, you have to follow the below syntax-

for file in /directory/path/*
do
   commands
done

Example of looping through directory using Bash for loop

for file in /home/madhav/*
do
  if [ -f $file ]
  then
    echo "$file is a file."
  elif [ -d $file ]
  then
    echo "$file is a directory."
  fi
done

Output of the above program

/home/madhav/main.sh is a file.
/home/madhav/java is a directory.
/home/madhav/version.txt is a file.
/home/madhav/factorial.py is a file.
/home/madhav/program.c is a file.

C-style Bash for loop

If you are from C or Java programming background then good news for you. Bash provides a version of for loop that has syntax similar to C and Java for loop.

C-style Bash for loop Syntax

for((initialization part; condition part; increment/decrement))
do
   commands
done

Example: Print half-pyramid using C-style for loop

rows=5
for((i=1; i<=rows; i++))
do
  for((j=1; j<=i; j++))
  do
    echo -n "* "
  done
  echo
done

Output of the above program

*
* *
* * *
* * * *
* * * * *