For Loop is an integral part of any programming language. It allows programs to iterate through a certain number of items.

For example, if you want to go through a list or array of ‘n’ items, you’d use a for Loop. Let’s take a simple example:

1Violet
2Indigo
3Blue
4Green
Rainbow Table

To perform any actions or to iterate the items in the above table, we require a For Loop.

Bash For Loop

In a bash script, For Loop syntax is as follows:

#!/bin/bash

for VAR in 1 2 3 4 5.....N

do

 ACTION 1

 ACTION 2

 .....

done

Bash For Loop is quite straightforward. The first line #!/bin/bash indicates that the code is a bash script. VAR stands for the temporary variable used For Looping. N indicates the maximum number of iterations. ‘do’ and ‘done’ start and stop the Loop, respectively. Actions are the commands that execute within the Loop.

We can execute Bash For Loop with different variables, like list, strings, integers, and arrays. This article will show a few common examples of the Bash For Loop.

You can directly execute these programs on the bash command line or save them in a file and execute the file using the Bash filename.sh command.

Reading Static List

Consider the following list – rainbowColorList = Violet, Indigo, Blue, Green, Yellow, Orange, Red

We can print the above string list using the Bash For Loop as follows:

#! /bin/sh

# Define the list

rainbowColorList=Violet,Indigo,Blue,Green,Yellow,Orange,Red

# Comma separator pattern using //,/

for colors in ${rainbowColorList//,/ }

do

   echo $colors

done

The output will be the list of items in a new line.

#Output

Violet
Indigo
Blue
Green
Yellow
Orange
Red

Reading an Array

The syntax for declaring an array is different. Use parentheses for each element (String).

rainbowArray=("Violet" "Indigo" "Blue" "Green" "Yellow" "Orange" "Red")

for colors in "${rainbowArray[@]}"; do

     echo "I like $colors"

done

‘@’ is used to iterate through each element in the array.

#Output

I like Violet
I like Indigo
I like Blue
I like Green
I like Yellow
I like Orange
I like Red

We can also use the For Loop to print the indexes and the array elements.

#Printing with index

rainbowArray=("Violet" "Indigo" "Blue" "Green" "Yellow" "Orange" "Red")

for i in "${!rainbowArray[@]}";

do

  echo "Color at index " $i " : " "${rainbowArray[$i]}"

  i=$((i+1));

done
#Output

Color at index 0 : Violet
Color at index 1 : Indigo
Color at index 2 : Blue
Color at index 3 : Green
Color at index 4 : Yellow
Color at index 5 : Orange
Color at index 6 : Red

Note that we use ‘!’ in the Loop to get the element index.

Iterating Range of Numbers

We can use Bash For Loop to iterate over a range of numbers.

#iterating over range of numbers

echo "Countdown begins..."

for N in {10..0}

do

    echo "$N"

done

The ‘..’ indicates a range of numbers.

#Output

10
9
8
7
6
5
4
3
2
1
0

We can also skip count numbers by specifying the range.

In the below example, we are skip counting by 3.

#iterating with skip counting

echo "Countdown begins..."

for N in {30..0..3}

do

    echo "$N"

done

The program above starts with 30 as the first number and counts down to 0. The last parameter in the for loop ‘3’ specifies the skip count number.

#Output

30
27
24
21
18
15
12
9
6
3
0

Strings and Characters

We can do a lot of interesting string operations with Bash For Loop.

For example, we can read each character of a string by using the ‘seq’ operator in a For Loop:

#read characters of a string

myword="welcome"

for i in $(seq 1 ${#myword})

do

 echo "${myword:i-1:1}"

done

Note that the ‘seq’ should start with 1 to get the first character first.

#Output

W
e
l
c
o
m
e

We can also print the strings separated by space one by one:

#read each word from a sentence

mysentence="Welcome to GeekFlare. One stop hub for all techies"

for word in $mysentence; do

    echo $word

done
#Output

Welcome 
to 
GeekFlare. 
One 
stop 
hub 
for 
all 
techies

Expressions

Similar to any other programming language like Java, we can place expressions inside a Bash For Loop.

for (( var=10; var>=0; var-- ))

do 

  echo "Counting down...$var"

done
#Output

Counting down...10
Counting down...9
Counting down...8
Counting down...7
Counting down...6
Counting down...5
Counting down...4
Counting down...3
Counting down...2
Counting down...1
Counting down...0

Reading Command-Line Arguments

To read from command-line arguments, we use the ‘read’ command. In the below example, we will get a few numbers from the user and print the sum using Bash For Loop. We use the variable total to store the intermediate and final total or sum of the numbers.

read -a array -p "Enter the numbers you want to add:"

total=0

for i in ${array[@]}; do

  let total+=$i

done

echo "Sum of the numbers is: $total"

The output is:

#Output

Enter the numbers you want to add: 3 4 66
Sum of the numbers is: 73

Finding Odd-Even Numbers

To find odd and even numbers between 1 to 10 (or any number N), we should use the if condition along with Bash for Loop. To determine an even number, we will divide the number by 2 and if the remainder is 0, then categorize it as even else odd.

#declare the list where the even and odd numbers will be sorted and kept

evennum=""

oddnum=""

for (( i=1; i<=10; i++ ))

do

remainder=$(( $i % 2 ))

if [ $remainder -eq 0 ]; then

 evennum="$evennum $i "

else

 oddnum="$oddnum $i "

fi

done

echo "Even numbers are: "$evennum

echo "Odd numbers are: "$oddnum

Note that we are giving the range as 10 in the above example. We can change this number to get even and odd numbers between any range. You can also try to read the number from the user using the ‘read’ command we learned in the previous section.

#Output

Even numbers are: 2 4 6 8 10
Odd numbers are: 1 3 5 7 9

Infinite Loop

Infinity or infinite Loop is a loop that doesn’t stop executing, and the program must be forced to stop using Ctrl+C. We can easily create an infinite loop using the ‘; ;’ operator inside the for Loop:

for (( ; ; ))

do

  echo "Welcome to Geekflare"

done
#Output

Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
Welcome to Geekflare
^C
$

Break Statement

Break statements are used to break from the Loop when an ‘if’ condition is satisfied.

for color in Violet Indigo Blue Green Yellow Orange Red

do

  if [[ "$color" == 'Green' ]]; then

    break

  fi

  echo "Searching for Green, the color now is $color"

done

echo "I found my color $color"

In this example, we are trying to find the color green. The For-Loop loops through each color, and once the green color is found, the program comes out of the Loop because of the break statement.

#Output

Searching for Green, the color now is Violet
Searching for Green, the color now is Indigo
Searching for Green, the color now is Blue
I found my color Green

Continue Statement

Continue is used to skip the current Loop and move to the next based on a certain condition. For example, if you don’t want to print the color ‘Green’ from our previous program, we can put continue, and all other colors except Green will be displayed.

for color in Violet Indigo Blue Green Yellow Orange Red

do

  if [[ "$color" == 'Green' ]]; then

    continue

  fi

  echo "$color"

done
#Output

Violet
Indigo
Blue
Yellow
Orange
Red

Final Words

We have covered the most common usages of a Bash For Loop, using strings, integers, arrays, and list. If you are learning Linux but have a Windows 10 machine, you can use the WSL feature and install Linux on your Windows machine.

You can then use the Linux terminal in a similar fashion to CMD.

Next, you can check out how to run bash scripts using Python.