10 Examples of Bash For Loops with Explanations

An essential component of any programming language is the for loop. It enables software to cycle through a set number of things.

For instance, you might use a “for Loop” to iterate through a list or array of ‘n’ objects. Take this easy case in point:

1Violet
2Indigo
3Blue
4Green

A for loop is necessary in order to execute any operations or iterate the entries in the above table.

Bash For Loop

The syntax for a for loop in a bash script is as follows:

#!/bin/bash

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

do

 ACTION 1

 ACTION 2

 .....

done

Bash For Loop is an easy game to understand. The initial line of the code, #!/bin/bash, identifies it as a bash script. VAR is an abbreviation for the momentary variable used in looping. The letter N denotes the most iterations possible. The Loop is started and stopped using the commands « do » and « done. » The instructions that run inside the Loop are referred to as actions.

Different variables, such as lists, texts, integers, and arrays, can be used in the Bash For Loop. A few typical Bash For Loop examples will be shown in this post.

You may run these scripts straight from the bash command line, or you can save them to a file and run the file using the Bash filename.sh command.

Reading Static List

Think about the list below: Violet, Indigo, Blue, Green, Yellow, Orange, and Red are all colours of the rainbow.

The Bash For Loop may be used to output the string list seen above as shown below:

#! /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 list of items in a new line will be the output.

#Output

Violet
Indigo
Blue
Green
Yellow
Orange
Red

Array reading

Declaring an array has a different syntax. For each element (String), use parentheses.

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

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

     echo "I like $colors"

done

The array’s elements are iterated through using the symbol « @ ».

#Output

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

The indices and array items can also be printed using the For Loop.

#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

Take note that we utilize the symbol « ! » to obtain the element index in the loop.

Range of Numbers Iteration

To iterate across a range of integers, we may use the Bash For Loop.

#iterating over range of numbers

echo "Countdown begins..."

for N in {10..0}

do

    echo "$N"

done

The ‘..’ denotes a range of numbers.

#Output

10
9
8
7
6
5
4
3
2
1
0

Choosing the range allows us to skip count numbers as well.

In the illustration below, we are skipping counting by 3.

#iterating with skip counting

echo "Countdown begins..."

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

do

    echo "$N"

done

The program in the example above counts down from 30 to 0 starting with 30 as the initial integer. The skip count is determined by the third argument of the for loop.

#Output

30
27
24
21
18
15
12
9
6
3
0

Characters and Strings

With the Bash For Loop, we are able to do a wide variety of useful string manipulations.

Using the’seq’ operator in a For Loop, for instance, we may read a string’s individual characters:

#read characters of a string

myword="welcome"

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

do

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

done

The’seq’ should begin with 1 to obtain the first character first, therefore keep that in mind.

#Output

W
e
l
c
o
m
e

We may also print the strings one by one, each gap between them:

#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

We are able to use expressions within a Bash For Loop, just as in any other programming language, such as Java.

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

The’read’ command is used to read from command-line parameters. In the example below, we will ask the user for a few integers and then use a Bash For Loop to output the total. To hold the initial, final, and sum of the numbers, we utilize the variable total.

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

Looking for Odd-Even Numbers

In addition to Bash for Loop, we should utilize the if condition to detect odd and even values between 1 and 10 (or any number N). Divide the number by two to discover if it is even or odd. If there is a zero as the residue, the number is considered even.

#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 in the example above, we are specifying a range of 10 values. This number may be changed to produce even and odd numbers in any range. Using the’read’ command that we learnt how to use in the previous section, you can also try to read the number from the user.

#Output

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

Infinite Loop

A program must be forced to end an infinite loop by pressing Ctrl+C. Using the ‘; ;’ operator inside the for Loop, we can quickly build an infinite loop:

for (( ; ; ))

do

  echo "Welcome to nftsarts"

done
#Output

Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
Welcome to nftsarts
^C
$

Statement of Break

When the ‘if’ condition is met, break statements are used to exit the loop.

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 instance, we’re looking for the colour green. When the green colour is identified, the program exits the loop because of the break statement, ending the For-Loop’s cycle of iterating through all the colours.

#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

Based on a certain circumstance, Continue is used to bypass the current Loop and go on to the next. For instance, if you don’t want the colour « Green » from our previous program to print, you may press continue and all other colours will be displayed instead.

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

Conclusion

We have discussed how to use a Bash For Loop with texts, integers, arrays, and lists, as well as other common data types. If you have a Windows 10 computer and are studying Linux, you can try the WSL functionality to install Linux on your Windows computer.

After that, you can start using the Linux terminal similarly to CMD.

Recommended For You

About the Author: Paul

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *