Exit “while” Loop Using “break” Statement in Bash [11 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

When you are working with bash loops and wish to exit from the loop before finishing it, you can do that using the break statement. The break statement is one of the most powerful tools that allows you to easily break a loop based on a specific condition. The conditions can be changed according to your requirements when you need to break. In this post, I will show you 11 practical examples of using the break statement within a while loop that will help you elevate your scripting skills.

Basics of “break” Statement

The break statement is a control structure used in various programming languages including Bash to break a loop. It allows the user to terminate a loop prematurely or switch statements based on a certain condition. Here’s the flow diagram of the break statement:

break statement flowchart

11 Examples to Exit “while” Loop in Bash Using “break” Statement

In a while loop, the break statement is used to break the loop. A loop can be interrupted based on one, or several conditions. The break statement can also be used to handle errors. In this section, I will look at 11 examples of using a break statement to interrupt the while loop.

1. Break a “while” Loop Based on a Single Condition

A break statement can break the while loop based on a single condition. The condition for terminating the loop in this example is [[ $n -eq 4 ]]. In this case, when the value of n becomes 4, the loop will terminate. Moreover, this script uses the -le (less than and equal to) and -eq (equal to) operators within a while loop which is the common comparison operator in Bash.

Now, follow the script to see how to break a while loop based on a single condition:

#!/bin/bash
n=0
while [[ $n -le 8 ]]; do
  echo $n
  if [[ $n -eq 4 ]]; then
    break
  fi
  ((n++))
done
EXPLANATION

The script initializes with a variable n with a value of 0. Inside the while loop, the condition $n -eq 4 checks whether n is equal to 4. If n is equal to 4, the break statement terminates the while loop. Otherwise, it runs as long as the value of n becomes less than and equal to 8 ($n -le 8). The value of n is incremented by 1 in each iteration with ((n++)).

break while loop based on a single condition

As you can see the while loop breaks when the number equals 4.

2. Based on Multiple Conditions Break a “while” Loop

The while loop can be terminated based on multiple conditions. For that, the conditions are set in the if statement with the help of the AND operator ($$) inside the loop. Now, check out the bash script to break a while loop based on multiple conditions using the break statement:

#!/bin/bash
n=0
while [[ $n -le 10 ]]; do
  if [[ $n -gt 5 && $n -lt 8 ]]; then
    break
  fi
  echo $n
  ((n++))
done
EXPLANATION

After assigning the value 0 to the variable n, while [[ $n -le 10 ]]; do starts the loop to iterate as long as the n is less than and equal to 10. But for the break statement, it breaks the loop when the value of the n is greater than 5 ($n -gt 5) and less than 8 ($n -lt 8). The echo command prints the current value of the n variable. ((n++)) increases the value of the n by 1 in every iteration.

break while loop based on a multiple conditions

Upon executing the script, it prints the numbers from 0 to 5 and the loop terminates when the number gets greater than 5 and less than 8.

3. Exit from a “while” Loop Based on Counter

Another way to end a while loop is to use the counter. In bash, the counter is a variable that is incremented by 1 in every iteration using the ((counter++)) syntax. When the counter reaches a certain value, it terminates the loop. Here’s the bash script to complete the task:

#!/bin/bash
counter=0
while [[ $counter -le 10 ]]; do
echo "Counter: $counter"
    ((counter++))
    if [ $counter -eq 6 ]; then
        break
    fi
done
EXPLANATION

This script initializes a variable counter to 0 and then enters a while loop. Inside the loop, echo "Counter: $counter" prints the current value of the counter variable. Then, it increments the value of the counter by 1 using ((counter++)).

After that, it checks whether the counter is equal to 6 using the condition if [ $counter -eq 6 ]. If this condition is true, it executes a break statement, which will exit the loop prematurely. If the condition is false, the loop will continue as long as the number is less than and equal to 10.

break while loop in bash based on counter

The picture shows that the loop terminates when the counter becomes 6.

4. Break an Infinite “while” Loop Based on User Input

An infinite while loop is a kind of loop that runs forever. However, a user can provide a specific input to break the infinite while loop. In this example, if the user type “y” in the question prompt, the infinite while loop will stop executing “Linuxsimply.com”. Follow the script below to understand how to break the infinite while loop based on user input:

#!/bin/bash
while true; do
    echo "Linuxsimply.com"
    read -p "Do you want to break? (y/n): " user_input
    if [ "$user_input" == "y" ]; then
        break
    fi
done
EXPLANATION

This script creates an infinite loop using while true. Inside the loop, it prints “Linuxsimply.com” and prompts the user to input either “y” or “n” to determine whether to break out of the loop. If the user enters “y”, the script executes a break statement, ending the loop. Otherwise, it continues the loop printing “Linuxsimply.com”.

break while loop based on user input in bash

The loop stops executing “Linuxsimply.com” when a user types “y” into the prompt.

5. Exit out of a “while” Loop Based on Command

It is possible to exit out of a while loop based on a command. In the following example, the ping command is used to check the reachability of the server “linuxsimply.com”. Once the command is executed successfully, the loop will come to an end. To do this, copy the bash script:

#!/bin/bash
server="linuxsimply.com"
while true; do
    if ping -c 1 "$server" &> /dev/null; then
        echo "Ping to $server successful! Exiting the loop."
        break
    else
        echo "Ping to $server unsuccessful. Retrying..."
        sleep 2
    fi
done
EXPLANATION

server="linuxsimply.com" sets the variable server to the value “linuxsimply.com”. while true; do initiates an infinite loop. Then if ping -c 1 "$server" &> /dev/null uses the ping command to send one ICMP echo request to the specified server linuxsimply.com. The &> /dev/null redirects both standard output and standard error to /dev/null to suppress the output. If the ping is successful, the script prints a success message and exits the loop using the break command.

If the ping is unsuccessful, the script prints an error message, waits for 2 seconds using the sleep 2 command, and then retries the ping in the next iteration of the loop.

break while loop based on command

The loop breaks as the ping command is successful.

6. Break a “while” Loop Based on Error

To handle errors, a break statement can be integrated with the $? special variable that checks whether a particular command is successful or not. If the $? variable returns 0, meaning that the command is executed successfully. When the variable returns more than 0, it indicates the failure of the command.

The following bash script will break a while loop when it encounters an error. Check out the script:

#!/bin/bash
while true; do
    df -h
    if [ $? -ne 0 ]; then
        echo "Error occurred. Exiting the loop."
        break
    else
        echo "Command executed successfully. Continuing..."
        sleep 2
    fi
done
EXPLANATION

while true; do initializes an infinite loop. Then df -h command displays disk space usage. if [ $? -ne 0 ] checks the exit status of the last command (df -h). If the exit status is not equal to 0, the script prints an error message and exits the loop using the break statement. If the exit status is 0, the script prints a success message, and the loop continues. The sleep 2 command introduces a pause of 2 seconds before going to the next iteration of the loop.

After running the script, you will get the following output displaying the usage of disk space:

break while loop based on error

As no error is encountered, the loop continues. You can type CTRL+C to exit out of the loop.

7. Based on a Correct Password Exit from a “while” Loop

In this example, the while loop will terminate based on a correct password. The loop breaks if the password does not match the actual password of the user. Here’s how:

#!/bin/bash
correct_password="linux"
while true; do
    read -p "Enter the password: " user_password
    if [ "$user_password" == "$correct_password" ]; then
        echo "Correct password! Access granted."
        break
    else
        echo "Incorrect password. Try again."
    fi
done
EXPLANATION

correct_password="linux" sets the correct password. Then the infinite while loop starts and prompts the user to enter a password with the read -p command. After that if [ "$user_password" == "$correct_password" ] checks whether the entered password matches the correct password (“linux”). If the user enters the correct password, it prints a success message and exits the loop. If the entered password is incorrect, it prints an error message and prompts the user to try again.

break bash while loop based on correct password

“li” is an incorrect password so it shows an error message. When the correct password “linux” is entered, the loop breaks with a success message.

8. Break a “while” Loop Based on Signal

The trap command is used here to catch the SIGINT signal usually produced by pressing Ctrl+C. After receiving the signal, it executes the break command to end the loop. To know more, check the script below:

#!/bin/bash
trap 'break' SIGINT
n=1
while [ $n -le 10 ]; do
    echo "Iteration number:$n"
   sleep 1
 ((n++))
done
EXPLANATION

trap 'break' SIGINT sets up a trap to capture the SIGINT signal (generated by pressing Ctrl+C) and executes the break command when the signal is received. n=1 initializes a variable n with the value 1. while [ $n -le 10 ]; do starts a while loop that continues as long as the value of n is less than or equal to 10. echo "Iteration number: $n" prints a message indicating the current iteration number. sleep 1 pauses the script for 1 second, simulating some work within each iteration. ((n++)) increments the counter n for the next iteration.

break while loop based on signal

When I pressed CTRL+C, the loop ended due to the signal.

9. Exit Out of a “while” Loop Based on File Existence

To exit out of a while loop based on file existence, the -e option is used inside the if condition that checks whether the specified file exists. Follow the script below to learn the complete process:

#!/bin/bash
while true; do
    read -p "Enter the filename: " filename
    if [ -e "$filename" ]; then
        echo "File '$filename' exists. Exiting the loop."
        break
    fi
done
EXPLANATION

After starting the infinite while loop, it prompts the user to enter a filename and stores the input in the variable “filename” with the read -p command. Then if [ -e "$filename" ] checks if the entered file exists, and repeats the process until an existing “filename” is provided. Once the existing filename is entered, the script prints a success message and exits the loop using the break command.

break bash while loop based on file existence

Since there is no “mou.txt” file, the loop continues. The loop ends when it discovers that the “hello.txt” file is present.

10. Break “while” Loop With Function Calls

The break statement can be executed with function calls. In this example, a function named positive_number is created first to check whether the input number is positive or negative, then the while loop will call the function and end the loop if the given number is positive. Check out the script to know the full process:

#!/bin/bash
positive_number() {
    local number="$1"
    if [ "$number" -gt 0 ]; then
        echo "Valid positive number. Exiting the loop."
        return 0
    else
        echo "Invalid number. Please enter a positive number."
        return 1
    fi
}

while true; do
    read -p "Enter a positive number: " n
    if positive_number "$n"; then
        break
    fi
done
EXPLANATION

positive_number function is defined to check whether a given number is greater than 0 (positive number) or not using the "$number" -gt 0 condition. Inside the while loop, the read command with the -p option is used to prompt the user to enter a number. The entered number is then passed to the positive_number function.

If the function returns 0 (indicating a valid positive number), the loop is exited using the break statement and prints “Valid positive number. Exiting the loop.” by the echo command. When the function returns 1 (indicating an invalid negative number), the loop continues and prints “Invalid number. Please enter a positive number.” until the user enters a positive number.

break while loop with function calls

The loop did not break when I entered negative numbers -1 and -2. When the positive number 1 is entered, the loop terminates.

11. Exit from Nested “while” Loops

Nested while loops contain one while loop within another while loop. When dealing with nested loops, the break statement in Bash can take an optional numerical argument to specify which loop to exit. Here, the break 2 statement is used to exit out of both loops. Follow the bash script:

#!/bin/bash
i=0
while [[ $i -lt 10 ]]; do
    j=0
    while [[ $j -lt 5 ]]; do
        echo "$i, $j"
        if [[ $j -eq 3 ]]; then
            echo "Breaking out of both loops."
            break 2  # Breaks out of both loops
        fi
        ((j++))
    done
    ((i++))
done
EXPLANATION

The outer loop runs while the variable i is less than 10 ($i -lt 10). Inside the outer loop, the inner loop runs as long as the variable j is less than 5 ($j -lt 5).

Within the inner loop, the script prints the values of i and j using the echo "$i, $j". It then checks if j is equal to 3. If true, it prints a message and uses break 2 to exit both the inner and outer loops. If j is not equal to 3, the inner loop continues until j is no longer less than 5. ((j++)) increments the value of j by 1 in each iteration.

After the inner loop completes, the outer loop increments the variable i using ((i++)), and the process repeats until i is no longer less than 10.

break nested while loops using break 2 statement

The script breaks out of both loops when j is equal to 3. If you remove the “break 2” statement, the script will continue until the outer loop completes even after j is equal to 3 in the inner loop.

To exit from an inner loop only, use break 1 statement like this:

#!/bin/bash
i=0
while [[ $i -lt 3 ]]; do
    j=0
    while [[ $j -lt 3 ]]; do
        echo "$i, $j"
        if [[ $j -eq 1 ]]; then
            echo "Breaking out of the inner loop."
            break 1  # Breaks out of the inner loop
        fi
        ((j++))
    done
    ((i++))
done
EXPLANATION

i=0 initializes a variable i to 0. while [[ $i -lt 3 ]]; do starts an outer loop that continues as long as the value of i is less than 3. j=0 initializes a variable j to 0 within the outer loop. while [[ $j -lt 3 ]]; do starts an inner loop that continues as long as the value of j is less than 3. echo "$i, $j" prints the values of i and j.

$j -eq 1 within if condition checks if the value of j is equal to 1. If true, it prints “Breaking out of the inner loop.” using the break 1 statement. ((j++)) increments the value of j by 1. ((i++)) increments the value of i by 1 for the next iteration of the outer loop.

break inner while loop in bash using break 1 statement

When j becomes 1, the script breaks out of the inner loop using “break 1” and allows the outer loop to continue executing.

Tips for Using “break” Statement in Bash “while” Loop

Use the break statement cautiously to exit out of the while loop to avoid unexpected results. Here are some tips on how to use the break command within the while loop:

  1. Use break command within the if conditional statement: It is great to use the break command within the if statement to break upon a specific condition when you want to avoid premature break.
  2. Try to use labels for nested loops: As there are multiple loops, consider using labels to break a particular loop.
  3. Always test code before running: Test your code before running using testing tools to check the errors.
  4. Be mindful of exit condition: If you do not provide an appropriate exit condition to end your loop, you may end up with an unwanted outcome.
  5. Use descriptive variable names: The names of the variables should be descriptive, which avoids ambiguities and simplifies the debugging process.
  6. Control signal utilizing “tap” command: Use the tap command that can break a loop after receiving a signal generated by pressing CTRL+C.
  7. Explain code using comments: Comments make the code easier to read and understandable. This is especially useful when you are dealing with complicated scripts.

Practice Tasks of Using “break” Statement in Bash “while” Loop

Practice the following to improve your understanding of how to use a break statement inside the Bash while loop to terminate it:

  1. Create a while loop that continues as long as the value of the variable reaches 15 and breaks a while loop when the value becomes 10.
  2. Write a script that uses a while loop to generate a sequence of even numbers up to 10. Break out of the loop when the loop variable becomes greater than or equal to 6.
  3. Make an infinite while loop that breaks when a user types “No” in the prompt.
  4. Generate nested while loops and break the inner loop when the variable value is greater than 4.

Conclusion

In conclusion, I have covered 11 examples of using the “break” statement inside a while loop. Additionally, you will learn how to use the break command effectively to prevent unwanted errors. Lastly, don’t forget to do the practice tasks. Good luck!

People Also Ask

How to break from loop in shell script?

To break from loop in n shell scripting, you can use the break statement. The break statement is typically used within loops to terminate the loop based on a certain condition. Here is an example bash script:

#!/bin/bash
count=1
while true; do
    echo "Iteration $count"
    if [ $count -eq 5 ]; then
        echo "Breaking out of the loop."
        break
    fi
    ((count++))
done

This script breaks the loop when the value of count equals 5.

What is while loop in shell script?

In a shell script, a while loop is a control structure that repeatedly executes a set of statements as long as a specified condition is true.

How do you break an infinite while loop?

To break an infinite while loop that runs indefinitely, use the break command inside the infinite while loop. Here’s a basic syntax for this:

#!/bin/bash
while true; do
    # Commands to be executed in each iteration of the loop
    if [ condition ]; then
        break
    fi
done

Replace the condition according to your preference when you wish to break the loop.

How do you break while true?

The while true creates an infinite loop. To break it, use the break statement within the loop.

What is the difference between break and continue?

The main difference between the break and continue statements is that the break command breaks the loop based on a specific condition whereas the continue command skips the rest of the commands for the current iteration and moves on to the next iteration.

What is exit criteria for while loop?

The exit criteria for the while loop is the condition specified in the while statement. The loop continues to execute as long as this condition remains true. Once the condition evaluates to false, the loop is exited. If you want to exit before finishing the loop, you can use the break command within the loop.

Related Articles


<< Go Back to “while” Loop in Bash | Loops in Bash | Bash Scripting Tutorial

Rate this post
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment