BASH Programming

How to Implement Loops in Bash

The loop is a major part of any programming language. The “for”, “foreach”, and “while-do” loops are used in Bash to solve different programming problems. Most of the repeating tasks can be done using the “for” loop and it is mainly used to iterate the loop finite numbers of times. The “while” loop is mainly used when the number of iteration of the loop is not predefined. Different uses of the “for” loop and the “while” loop are shown in this tutorial using multiple Bash scripts.

List of Contents:

    1. Use of the “For” Loop to Read a String
    2. Use of the “For” Loop to Read a List of Data
    3. Use of the “For” Loop to Read an Array
    4. Use of the “For” Loop to Read the Range of Values
    5. Iterate the Script Using the Three-Expression “For” Loop
    6. Use of the Infinite “For” Loop
    7. Use of the “For” Loop with Break Statement
    8. Use of the “For” Loop with Continue Statement
    9. Use of the “For” Loop to Read the Command-Line Arguments
    10. Use of the “For” Loop to Read an Associative Array
    11. Use of the “For” Loop with “Seq
    12. Use of the “For” Loop with Command
    13. Use of the Nested “For” Loop
    14. Use of the “While” Loop to Read a File
    15. Use of the “While” Loop with Multiple Conditions

Use of the “For” Loop to Read a Text

The simplest use of “for” loop is shown in the following script. A string of three words is parsed by the loop and printed each word in each line.

#!/bin/bash

# Read each word of the text
for val in Bash Scripting Language
do
   #Print the parsed value
   echo $val
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the “For” Loop to Read a List of Data

The method of printing a list of data using the “for” loop is shown in the following script. Here, four list items are parsed using the loop and each item is printed in each line.

#!/bin/bash

#Read the list of data
for val in "Bash" "Python" "Perl" "PHP"
do
    #Print each value of the list
    echo $val
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the “For” Loop to Read an Array

The method of reading each element of a numeric array using the “for” loop is shown in the following script. An array of four elements is declared in the script and the loop parses each value of the array and prints it in each line.

#!/bin/bash

#Declare an numeric array
declare -a products=( 'HDD' 'Monitor' 'Mouse' 'Keyboard' )

echo "Array values are:"
for val in "${products[@]}"
do
    #Print each array value
    echo "$val"
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the “For” Loop to Read the Range of Values

The method of calculating the sum of five input numbers using the “for” loop with the range of values is shown in the following tutorial. The “$sum” variable is used here to store the summation result and is initialized to 0 before iterating the loop and taking an input from the user. Five numbers are taken from the user in each iteration and the sum of the numbers are calculated.

#!/bin/bash

#Initialize the variable
sum=0

#Iterate the loop for 5 times
for n in {1..5}
do
   #Take a number from the user
   echo -n "Enter a number: "
   read num
   #Calculate the sum of the number
   ((sum+=$num))
done

#Print the sum of the numbers
echo "The sum of 5 numbers is $sum."

 
Output:

The following output appears after executing the script:


Go to top

Iterate the Script Using the Three-Expression “For” Loop

The three-expression “for” loop is the conventional way of using “for” loop for any programming language. The following script shows the use of the three-expression “for” loop in Bash to print the values of an array.

#!/bin/bash

#Declare an array of 4 elements
declare -a names=("Kamal" "Sabbir" "Zinia" "Jaber" "Jafar")

#Count the total elements of the array
len=${#names}

#Print the array values
echo "Array values are:"
for (( i=0; i<$len; i++ ))
do
    #Print each value of the array
    echo "${names[$i]}"
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the Infinite “For” Loop

The use of the three-expression “for” loop to define an infinite loop is shown in the following script. The loop is iterated for infinite times until the user presses “Ctrl+C”, takes the input value, and prints the value in each iteration.

#!/bin/bash

#Define an infinite loop
for (( ; ; ))
do
   #Take input from the user
   echo -n "Type a number: "
   read num
   #Print the input value
   echo "You have entered $num."
   #Print message for terminating the loop
   echo "Type CTRL+C to exit."
done

 
Output:

The following output appears after executing the script. According to the output, the “Ctrl+C” is pressed after taking the input values of 45 and 89:


Go to top

Use of the “For” Loop with the Break Statement

The “break” statement is used inside a loop to terminate from the loop based on the particular condition. Two command-line argument values are checked before starting the execution of the infinite “for” loop. If the argument values are non-empty, a menu will display for the user to perform four types of arithmetic operations or terminate from the loop. If the user presses 5, the first “if” condition inside the “for” loop will return true and the “break” statement will execute to terminate from the loop. Otherwise, the particular arithmetic operation is done based on the input value.

#!/bin/bash

#Read two values from the command-line arguments
num1=$1
num2=$2
#Check whether the values are non-empty or not
if [[ ! -z $num1 && ! -z $num2 ]]
then
    for (( ; ; ))
    do
        #Display the menu
        echo "1. ADD"
        echo "2. SUBTRACT"
        echo "3. MULTIPLY"
        echo "4. DIVIDE"
        echo "5. EXIT"
        read -p "Enter your choice: " answer

        #Terminate the loop if 5 is pressed
        if [ $answer -eq 5 ]
        then
             break
        #Add the numbers if 1 is pressed
        elif [ $answer -eq 1 ]
        then
             ((result=$num1+$num2))
        #Subtract the numbers if 2 is pressed
        elif [ $answer -eq 2 ]
        then
             ((result=$num1-$num2))
        #Multiply the numbers if 3 is pressed
        elif [ $answer -eq 3 ]
        then
             ((result=$num1*$num2))
        #Divide the numbers if 4 is pressed
        elif [ $answer -eq 4 ]
        then
             ((result=$num1/$num2))
        fi
        echo "The result is $result."
    done
fi

 
Output:

The following output appears after executing the script with the argument values of 20 and 5. Here, “1” is taken as the first input and the sum of 20 and 5 is printed. Next, “5” is taken as the second input that terminates the loop:


Go to top

Use of the “For” Loop with the Continue Statement

The “continue” statement is used inside a loop to continue the next iteration of the loop by omitting a particular statement(s) of the loop. In the following script, a “for” loop is used to iterate for 10 times and find out those numbers between 1 to 10 which are divisible by 5. The “continue” statement is executed for the numbers which are not divisible by 5.

#!/bin/bash

echo "List of numbers divisible by 5 are:"
#Iterate the loop for ten times
for n in {1..10}
do
    #Check whether the number is divisible by 5 or not
    if [ $(($n%5)) -ne 0 ]
    then
        #Continue the loop if the number is divisible not divisible by 5
        continue
    fi
    #Print the numbers which are divisible by 5
    echo "$n is divisible by 5."
done

 
Output:

The following output appears after executing the script. Five (5) and ten (10) are the numbers which are divisible by 5 and these are printed in the output:


Go to top

Use of the “For” Loop to Read the Command-Line Arguments

The method of reading the command-line argument values using “for” loop is shown in the following script. The “$@” symbol is used with the “for” loop to read each argument value of the command-line. A counter variable is used in the script to print the argument number with the argument value.

#!/bin/bash

#Initialize a counter
counter=1;

#Iterate the read argument values
for val in "$@"
do
    #Print each argument value
    echo "Argument $counter: $val";
    #Increment the counter
    ((counter++))
done

 
Output:

The following output appears after executing the script with the argument values of 12, 56, and 23:


Go to top

Use of the “For” Loop to Read an Associative Array

The method of reading the keys and values of an associative array using “for” loop is shown in the following script. An associative array of four elements is defined in the script. Each key of the array is parsed by the loop in each iteration and the value of the corresponding key with the key value is later printed.

#!/bin/bash

#Declare an associative array
declare -A marks=( [56345]=90 [34123]=87 [45231]=64 [87234]=70 )

#Iterate the loop to keys of the array
for k in ${!marks[@]}
do
     #Print each key and value of the array
     echo "ID-$k obtained ${marks[$k]} marks."
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the “For” Loop with “Seq”

The following script shows the use of “seq” command with the “for” loop. Seven sequential dates are generated using the “seq” command here. The “date” command is used to read the current month value in short form and used this value to generate the date.

#!/bin/bash

#Read the short form of the current month value
month=`date +%b`

#Iterate the loop for 7 times
for i in $(seq 7)
do
    #Generate the date value
    val="$i-$month-2023"
    #Print the date
    echo "Generated date is $val"
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the “For” Loop with the Bash Command

The Bash command that generates a list of output can be parsed using the “for” loop. The following script prints the list of all text files from the current location that starts with the “t” character.

#!/bin/bash

#Read all text files that start with 't'
for val in $(ls t*.txt)
do
    #Print the filename
    echo $val
done

 
Output:

The following output appears after executing the script:


Go to top

Use of the Nested “For” Loop

The method of generating a series of values using the nested “for” loop is shown in the following script. Here, the outer “for” loop iterates for three times and the inner “for” loop iterates for four times.

#!/bin/bash

#Outer loop
for l1 in {A..C}
do
    #Inner loop
    for l2 in {1..4}
    do
        #Print the merged value
        echo -n "$l1$l2 "
    done
done
#Add newline
echo

 
Output:

The following output appears after executing the script:


Go to top

Use of the “While” Loop to Read a File

The use of “while” loop to read the content of a file is shown in the following script. Here, the filename passes in the command-line argument and the “while” loop reads the content of the file line by line.

#!/bin/bash

#The loop will parse each line of the file
#in each iteration
while read line; do
      #Print each line
      echo $line
#Read the filename from the command-line argument
done < $1

 
Output:

The following output appears after executing the script. The content of the “temp.txt” is printed in the output:


Go to top

Use of the “While” Loop with Multiple Conditions

The method of using the “while” loop with multiple conditions is shown in the following script. A numeric value is taken from the user and the loop starts the iteration if the value is greater than 10 and the value is even. In each iteration, the value is printed and decremented by 2.

#!/bin/bash

#Take a number from the user
read -p "Enter a number:" num

if [ ! -z $num ]
then
    #Check two conditions for the while loop
    while [ $num -gt 10 ] && [ $(($num%2)) -eq 0 ]
    do
        #Print the number
        echo "$num is even."
        #Decrement the number by 2
        ((num=$num-2))
    done
fi

 
Output:

The following output appears after executing the script for the input value of 16:


Go to top

Conclusion

Different uses of the Bash loop are shown in this tutorial using multiple Bash scripts that will help the Bash users to know the purposes of using the Bash loop and use it in their script properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.