Bash For Loop and While Loop Examples

Like any other scripting language, Bash also has support for loops.

Loops are great for doing repetitive tasks. We can make use of for loops and while loops in our Bash scripts.

Bash For Loop

The syntax of the for loop is:

for VARIABLE in PARAM1 PARAM2 PARAM3
do
  // scope of for loop
done

The for loop will execute for each parameter. The parameters can be numbers, range of numbers or strings, etc.

Bash For Loop Example

This simple example prints numbers, 1 to 5 using the for loop:

#!/bin/bash

for i in 1 2 3 4 5
do
   echo "$i"
done

Output:

1
2
3
4
5

Bash For Loop - Print Range of Numbers

We can also define a range of numbers to loop through:

For example:

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

Output:

1
2
3
4
5

Bash Loop Through Strings

We can also use the for loop to loop through string parameters:

#!/bin/bash

for day in MON TUE WED THU FRI SAT SUN
do
   echo "$day"
done

Output:

MON
TUE
WED
THU
FRI
SAT
SUN

Bash For Loop - C Style

We can also use a C-style syntax to write the for loop. For example:

#!/bin/bash

for ((i=1; i<=5; i++))
do
  echo "$i"
done

Output

1
2
3
4
5

For Loop to Print List of Files in Current Directory

To list all the files in the current directory using the bash for loop, we use:

#!/bin/bash

for fname in ./
do
  ls -l $fname
done

Bash While Loop

Bash also support while loops. While loops execute a set of instructions until a condition evaluates to true.

The syntax for the Bash while loop is:

while [condition]
do
  //execute instructions
done

The condition is evaluated before executing any instructions. Therefore, it is necessary to have a means of updating the condition, otherwise the loop will execute forever.

Bash While Loop Example

The following is a simple while loop that prints numbers 1 to 5. The loop is terminated when number is greater than 5.

#!/bin/bash

num=1
while [ $num -le 5 ]
do
   echo "$num"
   let num++
done

Bash C-Style While Loop

Like the for loop, we can also write the bash while loop in a C-style like language.

For example:

#!/bin/bash

num=1
while((num <= 5))
do
   echo $num
   let num++
done