Friday, November 15, 2024
Google search engine
HomeGuest BlogsBash break: How to Exit From a Loop

Bash break: How to Exit From a Loop

Introduction

In Bash scripting, a break statement helps provide control inside loop statements. Instead of waiting until the end condition, a break statement helps exit from a loop before the end condition happens.

The control loop statements (break and continue) combine logically with conditional statements such as if elif else to create special situations inside loops.

This tutorial teaches you how to use the break statement efficiently in Bash script loops.

Bash break: How to Exit From a LoopBash break: How to Exit From a Loop

Prerequisites

  • A machine running macOS or Linux.
  • Bash scripting basics (such as writing and running a script).
  • A text editor to write the Bash script examples, such as nano.

Bash break Statement

The break statement ends the current loop iteration and exits from the loop. When combined with a condition, break helps provide a method to exit the loop before the end case happens.

Bash break loop state diagramBash break loop state diagram

The Bash break statements always apply to loops.

The syntax is:

break <integer>

The integer value is optional, and it is 1 by default. The number defines the depth of the break for nested loops. Therefore, to break from a nested for loop, use break 2.

Bash break Examples

The examples below demonstrate how to exit from different loop types using the break statement. The examples include:

Each Bash script example below comes with an explanation.

Breaking from a while Loop

Use the break statement to exit a while loop when a particular condition realizes. The following script uses a break inside a while loop:

#!/bin/bash

i=0

while [[ $i -lt 11 ]] 
do
        if [[ "$i" == '2' ]]
        then
                echo "Number $i!"
                break
        fi
        echo $i
        ((i++))
done

echo "Done!"
while_break.sh script codewhile_break.sh script code

Each line in the script does the following:

  • Line 3 defines and sets the variable i to 0.
  • Line 5 starts the while loop. The end condition is when the variable is less than eleven ($i -lt 11).
  • Line 7 performs a check using an if statement. When the variable equals two ("$i" == 2), the program exits the while loop using the Bash break statement on line 10. In that case, the code jumps to line 16. If the variable is a different number, the script continues as expected on line 12.

Execute the script to see the results.

while_break.sh terminal outputwhile_break.sh terminal output

The program lists numbers up to 2 and exits the script.

Using break Inside for Loops

A for loop increments a variable automatically. To add a conditional statement and exit a for loop early, use a break statement. The following code shows an example of using a break within a for loop:

#!/bin/bash

for i in {1..10}
do
        if [[ $i == '2' ]]
        then
                echo "Number $i!"
                break
        fi
        echo "$i"
done

echo "Done!"
for_break.sh script codefor_break.sh script code

When the integer value equals two ($i == '2'), the program prints a message and exits the for loop thanks to the break statement.

for_break.sh terminal outputfor_break.sh terminal output

As a result, running the script ends the program when the variable i reaches two and jumps to the last line of code.

Breaking from an until Loop

A Bash until loop is one of the three fundamental loop constructs. Add a break statement to control the program flow and exit the loop under a different condition.

Below is an example program:

#!/bin/bash

i=0

until [[ $i -gt 10  ]]
do
        if [[ $i -eq 2  ]]
        then
                echo "Number $i!"
                break
        fi
        echo $i
        ((i++))
done

echo "Done!"
until_break.sh script codeuntil_break.sh script code

Although the until loop contains an end condition ($i -gt 10), the loop body contains another condition ($i -eq 2). Since the second condition happens before the first, the program enters the if statement’s body, which contains a Bash break statement to exit from the loop.

until_break.sh terminal outputuntil_break.sh terminal output

Running the script demonstrates that the program ends when the variable i reaches the value 2.

Using break Inside a select Loop

The select command creates menus and behaves like an infinite loop, even though it’s not one of the primary loop constructs. To exit the select statement elegantly, make a case for which the program ends and use break to leave the loop.

The code below demonstrates a textual number guessing game using a select statement:

#!/bin/bash/

PS3="Guess my favorite number: "

select i in {1..10}
do
        echo "Selected number: $i"
        if [[ $REPLY -eq 2 ]]
        then
                echo "Correct! $i is my favorite. Thanks for playing!"
                break
        fi
        echo "Not my favorite. Try again!"
done
select_break.sh script codeselect_break.sh script code

The code does the following:

  • Line 3 displays the instructional message. The select statement prints this message after listing all the options and after each incorrect guess.
  • Line 5 starts the select statement and defines the options as numbers 1 to 10.
  • Line 8 checks if the selected number equals 2, which is the correct guess. If the check passes, the Bash break statement helps exit the loop and ends the game.

Run the script to play the number guessing game.

select_break.sh terminal outputselect_break.sh terminal output

Input different values to see the results.

To develop the script further, try adding an elif statement to check for out of range inputs or change it to a case statement to consider various input situations.

Conclusion

After going through the examples in this tutorial, you know how to use the break statement to control a loop flow.

Next, learn how to use Bash comments to document the scripts from this tutorial.

Was this article helpful?
YesNo

RELATED ARTICLES

Most Popular

Recent Comments