Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • 1. Introduction
  • 2. Syntax
  • 3. Using Bash while loop
  • 4. Example
  • 7. Conclusion

How to Use While Loop in Bash for Efficient Scripting

PreviousBash Script for Counting Lines in a FileNextBash basename Command with Examples

Last updated 1 year ago

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=1while [ $x -le 5 ]; do echo "x is $x" x=$(($x+1)) sleep 1done echo "x after the loop is $x"

Let’s run the script and observe what happens:

  • 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=1y=5while [[ $x -le 5 && $y -ge 3 ]]; do echo "x is $x, y is $y" x=$(($x+1)) y=$(($y-1)) sleep 1done 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=1while true; do echo "x is $x" x=$(($x+1)) sleep 1done

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=6while [ $counter -ge 1 ]; do echo "counter is $counter" if [[ $counter == 3 ]]; then break fi counter=$(($counter-1)) sleep 1done

We apply the break command when the counter hits 3.

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

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

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>

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

#!/bin/bash file=testFile.txtwhile read -r line; do if [[ "${line: -1}" == "!" ]]; then echo "$line" sleep 1 fidone < "$file"

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

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.

The 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.

read
bash while continue statement
bash Infinite while loop
the output of bash while single condition
bash while break statement
sample file
reading from the sample file using bash while