How to Use While Loop in Bash for Efficient Scripting

Written by: Madhur Batra   |   Last updated: May 5, 2023

1. Introduction

In any programming language, loops are one of the most important building blocks. They help us to run commands in an iteration as long as the guard condition is satisfied. Bash provides for, while, and until constructs to write looping blocks. In this article, we will discuss the working of the while loop in detail.

2. Syntax

Bash while loop follows the syntax:

while <CONDITION>
do
 <STATEMENTS>
done

The conditions following the while command are evaluated in each iteration. If the condition evaluates to true, it enters the loop and executes the statements. If the condition evaluates to false, it terminates the loop and begins executing the statements following the while loop.

3. Using Bash while loop

Let’s take an example to demonstrate how to write a simple while loop to count the numbers from 1 to 5.

#!/bin/bash

x=1
while [ $x -le 5 ]; do
       echo "x is $x"
       x=$(($x+1))
       sleep 1
done

echo "x after the loop is $x"

Let’s run the script and observe what happens:

the output of bash while single condition
  • x is initialized to 1. 
  • On each iteration, the condition x <= 5 is evaluated. If the condition is true, the value of x is printed and incremented by 1.
  • Finally, when x = 6, it fails the condition and the loop terminates.

We can also create compound conditions by combining multiple simple conditions using logical operators.

#!/bin/bash

x=1
y=5
while [[ $x -le 5 && $y -ge 3 ]]; do
       echo "x is $x, y is $y"
       x=$(($x+1))
       y=$(($y-1))
       sleep 1
done

echo "x after the loop is $x"
echo "y after the loop is $y"
  • In this loop, we have two control conditions joined by the logical AND (&&) operator. 
  • Both the conditions x <= 5, and y >= 3 must be individually satisfied for the control to enter the while loop.
  • If the compound condition is satisfied, the control enters the while loop. x is incremented and y is decremented by 1.

On executing the script:

The condition is satisfied when the values of x, y are (1, 5) up to (3, 3). In the next iteration, y is equal to 2 and fails the condition y >= 3.

3.1. Infinite while loop

Infinite loops are loops that continue running forever and never terminate. The control condition always evaluates to true.

They are really useful when we need to write a long-running operation such as a background thread or a daemon.

We can create Infinite while loops by using the while statement and setting a condition that always evaluates to true. Let’s take an example:

#!/bin/bash

x=1
while true; do
       echo "x is $x"
       x=$(($x+1))
       sleep 1
done
bash Infinite while loop

In this script, we continue running the loop forever and terminate only when the user provides a SIGINT interrupt (Ctrl + C).

3.2. Control statements

Bash also provides built-in break and continue statements to control the behavior of the loop.

3.2.1. break

The break command helps to forcefully terminate the loop and pass the execution control to the statements following the loop.

Consider the following example:

#!/bin/bash

counter=6
while [ $counter -ge 1 ]; do
       echo "counter is $counter"
       if [[ $counter == 3 ]]; then
               break
       fi
       counter=$(($counter-1))
	 sleep 1
done

We apply the break command when the counter hits 3.

bash while break statement

Observing the output, we see the loop is terminated prematurely on executing the break command.

3.2.1. continue

The continue command is used to skip an iteration and continue the execution from the next iteration.

It is particularly helpful when we need to ignore the statements within the loop only when a specific condition is true and resume afterwards.

Let’s take the following example:

#!/bin/bash

counter=1
while [ $counter -le 10 ]; do
       counter=$(($counter+1))
       if [[ $((counter-1)) == 5 || $((counter-1)) == 6 ]]; then
               continue
       fi
       echo "counter is $(($counter-1))"
       sleep 1
done

In this script, we are counting the numbers from 1 to 10 but ignoring 5, 6.

bash while continue statement

We see the iterations are skipped when the counter is 5 or 6. The numbers 1-4 and 7-10 are printed on the stdout.

4. Example

The while loop comes in really helpful when trying to read the contents of a file. It provides a simple syntax to iterate over the file one line at a time.

while read -r line; do
 <STATEMENTS>
done < <FILENAME>

The read command is used in the while loop and the file is passed to the read command using the input redirection operator (<). This lets the while loop read lines in the file until there are no more lines left.

Let’s take a file and print all the lines that end with an exclamation(!) using the while loop.

sample file
#!/bin/bash

file=testFile.txt
while read -r line; do
       if [[ "${line: -1}" == "!" ]]; then
               echo "$line"
               sleep 1
       fi
done < "$file"

We match the last character in the line variable with ‘!’. If it matches, we print the line to the stdout.

reading from the sample file using bash while

7. Conclusion

  • Bash provides built-in support for a for, while, and until loops like other programming languages.
  • While loop uses the construct: continue iterations as long as the control condition remains satisfied.
  • The loop conditions can be created using any boolean statement. Compound conditions can also be created by joining multiple single conditions using logical operators. 
  • Infinite loops can be created using loop conditions that always evaluate to true. But, using infinite loops is not considered a good programming practice because it may introduce bugs or cause the script to hang if break conditions are not handled appropriately.
  • Bash provides break and continue control commands to be used in the loops. These help to prematurely terminate the loop or skip specific iterations. However, care must be taken to avoid their overuse since they increase the complexity of the script.
  • Bash offers a simple syntax to read the contents of the file one line at a time by using the read command in the while loop.

About The Author

Madhur Batra

Madhur Batra

Madhur Batra is a highly skilled software engineer with 8 years of personal programming experience and 4 years of professional industry experience. He holds a B.E. degree in Information Technology from NSUT, Delhi. Madhur’s expertise lies in C/C++, Python, Golang, Shell scripting, Azure, systems programming, and computer networking. With a strong background in these areas, he is well-equipped to tackle complex software development projects and contribute effectively to any team.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment