Bash while Loop | Explained

The loops in shell scripts are used for automation purposes, whereas the while loops in bash are commonly used in various situations to automate tasks and simplify your code. The while loop allows the user to check a condition for a specific number of iterations, conditionally check a condition, and skip the desired iteration.   

This guide will cover fundamental and advanced usage of the while loop with the below timeline:

Let’s start with the basic understanding of the while loop.

What is Bash while Loop?

A while loop executes code continuously based on a specific Boolean condition. When the specified condition is true, the while loop will continue to execute. After the Bash while loop condition is false, the loop will terminate, and the program will continue to run any code that comes after the loop.

The syntax of the bash loop is as follows:

while [condition]
do
       Commands
done

Let’s get to know the syntax line-by-line:

  • while: It shows that the while loop is executed here.
  • condition: The while loop will check until the condition is true.
  • do: The body of the while loop starts here.
  • Commands: Put all the executable commands here.
  • done: The while loop body is closed here.

The while loop can also be written in a single line as:

while [condition]; do Commands; done

Let’s check the usage of the while loop.

How to Use Bash while Loop?

The while loop can be used in different ways to check the condition, which will be discussed in this section.

Use while Loop to Iterate for Specific Times

The basic use of the while loop is to iterate through the body of the while loop to match the condition. For instance, we declared the variable “i=1”, which will be checked within the body until the “i” variable is less than or equal to “5”. Once it is greater than 5, the while loop is not satisfied now; the loop will be terminated:

#!/bin/bash

i=1
while [ $i -le 5 ]
do
    echo "Hello $i"
    (( i++ ))
done

The single-line syntax for the above bash script code will be:

#!/bin/bash
i=1 ; while [ $i -le 5 ] ; do  echo "Hello $i"  (( n++ )) ; done

To check the while loop output, run the bash script using:

$ bash while.sh

The output shows that the while loop is iterated from 1 to 5 then the while loop terminates.

Use while Loop to Write Into a File

The while loop can be used to write the content line by line into a file. For instance, the code below will write the testfile.txt file’s content with the read command, which will take the user input. The echo command will write the user input to the specified file:

Note: The content will append to the file, not overwrite, and to quit the editor, press the “Ctrl + D”.

#! /bin/bash

file=testfile.txt
echo "Add Content into File $file"
while read line
do
    echo $line >> $file
done

For running the bash script code use:

$ bash while.sh

To view the “testfile.txt” content, use the following command:

$ cat testfile.txt

The output verifies that the user input is appended to the file.

Use while Loop to Read File

The while loop can also read the file’s content line-by-line. For instance, if we want to read the “/etc/group” file content using the while loop, the below code will be used:

#!/bin/bash

file=/etc/group
while read -r line; do
  echo $line
done < "$file"

To read the content with the adobe while loop script, utilize below command to execute:

$ bash while.sh

The “/etc/group” file content is displayed in the output.

Use while Loop With Break Statement

The “break” and “continue” statements are used within the while loop to control the loop. The break statement directly exits the loop when the condition is matched. For instance, the below code will loop through 1 to 5 in normal execution, but we have put the break statement when the variable is “3”, which means the loop will automatically exit when the variable is “3”:

#! /bin/bash

i=0
while [ $i -lt 5 ]
do
  ((i++))
  if [[ "$i" == '3' ]]; then
    break
  fi
  echo "The Number is: $i"
done

For checking the output run the above bash shell script code:

$ bash while.sh

The output shows that the while loop breaks at 3 and terminates the loop.

Use while Loop With Continue Statement

The “continue” statement will skip the present iteration and proceed to the next iteration. The primary function of the continue statement is to skip a particular iteration while running other iterations normally.

For instance, the below continue statement is at variable “3”, which will skip the loop iteration 3 and execute the rest normally:

#! /bin/bash

i=0
while [ $i -lt 5 ]
do
  ((i++))
  if [[ "$i" == '3' ]]; then
    continue
  fi
  echo "The Number is: $i"
done

Let’s utilize the below command to run the bash script:

$ bash while.sh

The output shows that the iteration when the variable is “3” is skipped while the other loops work normally.

Use Conditional while Loop

The while loop is commonly used with conditions to perform specific tasks until the condition is satisfied, then terminate the loop. For instance, if we want to terminate the loop in case the first user input for the below code is “0”, else the while loop will continue printing the sum for the user input numbers:

#!/bin/bash  
while :
do
       read -p "Enter Two Numbers: " x y
       if [ $x -eq 0 ]
       then
              break
       fi
       sum=$(( x + y ))
       echo $sum
done

Execute the bash shell script, using the below command:

$ bash while.sh

The output shows that the terminal exits when the first input is “0”.

Use while Loop as Infinite Loop

If you want to run the while loop infinitely, the below syntax is used, which includes a colon (:) instead of the condition and body of the while loop containing the executable commands. For instance, to execute the “echo” command infinitely using the bash script, utilize the below-mentioned script:

#!/bin/bash
while :
do
       echo "Hello"
done

To run the while loop script, use:

$ bash while.sh

The output will run infinitely, but you can press “Ctrl + C” to terminate the loop.

Use while Loop to Evaluate Command Line Options With getopts

The while loop can be used to evaluate the options using the command line in Linux with the getopts command and case statement. We can write the options (in this case: a, b, c) with the getopts and the variable (option), which will be matched within the while loop body.

The printf command in the code is used to display the details about the options the user has entered:

To evaluate the options with the terminal, let’s put a name with “a” option, location with “b” option and field with “c” option as shown below:

#!/bin/bash
while getopts a:b:c: option
do
        case "${option}"
        in
           a) userName=${OPTARG};;
           b) location=${OPTARG};;
           c) field=${OPTARG};;
           *) echo "Invalid option"
              exit 1;;
        esac
done printf "Your Details are:\nUser Name :$userName\nLocation :$location\nField :$field\n"
$ bash while.sh -a itslinuxfoss -b USA -c content-writer

The printf command output is displayed on the screen.

This is all about the while loops in Bash.

Conclusion

The bash while loop is used to check the condition repeatedly while the condition is true. The while loop is used to iterate for specific times and write or read the file’s content line-by-line. Moreover, the bash while loop can be used conditionally with break and continue statements to automate tasks.