Ways to Stop While Loop When Reading Lines in a Shell Script/Bash?

When working with shell scripting, loops are essential for automating tasks that require executing commands repeatedly. While loops are commonly used to read lines from a file or input, it can be a tricky situation to stop the loop once it has started. 

This article will explore different methods to stop a while loop when reading lines in a shell script:

  • Understanding While Loops
  • Method 1: Using Break Statement
  • Method 2: Using Conditional Expression
  • Method 3: Using Flags

Understanding While Loop

Before diving into the methods to stop a while loop, let’s first understand what a while loop is and how it works in shell scripting. A while loop executes the commands repeatedly until the condition becomes false.

Here’s the syntax for a while loop in shell scripting:

while [ condition ]
do
    # code to be executed
done

In the above syntax, the condition is checked at the beginning of each iteration, and if it evaluates to true, the code inside the loop is executed until it becomes false.

The three different methods will be discussed to stop a while loop when reading lines which are listed below.

Method 1: Using Break Statement

The content of the text file that will be used in the shell script can be shown below:

$ cat file.txt

The break statement is used to terminate the execution of a while loop. When used inside a while loop, it will immediately exit the loop and continue executing the code outside the loop as shown in the example below:

#!/bin/bash
while read line
do
    # code to be executed
    if [ condition ]
    then
        break
    fi
done < file.txt

The breakdown of the above code is explained below:

  • This Bash script will read lines from a file called file.txt
  • The while read line loop iterates over each line in the file, executing the code inside the loop for each line.
  • The if condition will execute if it is true, which results in executing the break to terminate the script.

The actual code example is given below:

#!/bin/bash
while read line
do
    # Check if the line contains the word "error"
    if [[ $line == *"error"* ]]
    then
        echo "An error occurred: $line"
        break
    fi
    # Process the line if no error was found
    echo "Processing line: $line"
done < file.txt

The explanation of the code is mentioned below:

  • In this example, each line will be checked in “file.txt” contains the word “error” by using the [[ $line == *”error”* ]] condition. 
  • If an error is found, a message will be printed using echo and exit the loop using the break command.
  • If no error is found, all lines will be printed normally.

The script’s output can be seen below by executing the bash script below:

$ bash bash_file.sh

It can be seen that the while loop stops the execution when the word “error” is found in the file.txt text file.

Method 2: Using Conditional Expression

Another way to stop a while loop is to use a conditional expression in the loop’s condition. The conditional expression will evaluate to false, and the loop will exit when a particular condition is met. Here’s an example of how to use a conditional expression to stop a while loop:

while [ condition ] && read line
do
    # code to be executed
done < file.txt

In the above example, the while loop will continue to execute if the condition is true, and there are lines to be read from the file. Once there are no more lines to be read, the loop will exit.

An example of such a scenario is mentioned below:

#!/bin/bash
while [ -f "file.txt" ] && read line
do
    # Check if the line contains the word "error"
    if [[ $line == *"error"* ]]
    then
        echo "An error occurred: $line"
        continue
    fi
    # Process the line if no error was found
    echo "Processing line: $line"
done < file.txt

The explanation of the above code is mentioned below:

  • In this example, the “file.txt” is considered a regular file using the -f flag in the condition. If the file exists and is a regular file, the loop will continue to execute.
  • In each line of the file.txt, the word “error” will be searched by using the [[ $line == *”error”* ]] condition. 
  • If this word is found, a message will be printed, and the next iteration will be skipped using the continue command.
  • If no error is found, each line will be executed normally.

The code output can be seen by executing the bash script below:

$ bash bash_file.sh

Method 3: Using Flags

Flags are variables used to control a program’s flow. You can use flags to stop a while loop when reading lines, and one of its examples is mentioned below:

stoploop=false
while read line && [ "$stoploop" = false ]
do
    # code to be executed
    if [ condition ]
    then
        stoploop=true
    fi
done < file.txt

The breakdown of the above code is listed below:

  • The while loop is used to read lines from a file called file.txt
  • The stoploop flag is initially set to false. 
  • The condition is checked at the beginning of each iteration, and if it evaluates to true, the stoploop flag is set to true, which will exit the loop.

An example of such code is written below:

#!/bin/bash
stoploop=false
while read line && [ "$stoploop" = false ]
do
    # Check if the line contains the word "stop"
    if [[ $line == *"error"* ]]
    then
        echo "Stop signal received: $line"
        stoploop=true
    fi
    # Process the line if stop signal was not received
    if [ "$stoploop" = false ]
    then
        echo "Processing line: $line"
    fi
done < file.txt

The explanation of the above code is explained below:

  • A loop is being used to read lines from a file called “file.txt”. The loop will exit early if a stop signal is received.
  • The stop signal is identified by checking if each line in the file contains the word “error” using the [[ $line == *”error”* ]] condition.
  • If a stop signal is found, a message will be printed using echo and set stoploop=true to exit the loop.
  • If a stop signal is not found, the line will be processed by printing a message to the console.

The output of the code can be seen by executing the below bash script

$ bash bash_file.sh

It can be seen that the script stops the execution of the code when it receives the “error” text on the file.txt

Conclusion

Stopping a while loop when reading lines in a shell script is essential to control the flow of your program. We have explored three different methods to stop a while loop: using the break statement, using a conditional expression, and using flags.