BudiBadu Logo
Samplebadu

Bash by Example: Loop Control (Break)

Bash 5.0+

Exiting a loop prematurely using the break statement to terminate loop execution when a specific condition is met, implementing early termination patterns for search operations, optimizing loop performance by avoiding unnecessary iterations, and understanding break behavior in nested loops.

Code

#!/bin/bash

echo "Searching for 5..."

for i in {1..10}; do
    echo "Checking $i"
    
    if [ $i -eq 5 ]; then
        echo "Found 5! Stopping."
        break
    fi
done

echo "Loop finished."

# Break from nested loops
echo -e "\nNested Loop Break:"
for i in 1 2 3; do
    for j in A B C; do
        echo "$i-$j"
        if [ "$j" == "B" ]; then
            # break 2 exits BOTH loops
            break 2
        fi
    done
done
echo "Exited both loops."

Explanation

The break statement is used to terminate the execution of a loop immediately. Control passes to the first command after the done keyword. This is commonly used when searching for an item and stopping once it's found.

Bash allows breaking out of multiple levels of nested loops. By default, break exits only the innermost loop (equivalent to break 1). Providing a number, like break 2, tells Bash to exit that many levels of enclosing loops.

Using break can make logic cleaner by avoiding complex conditional checks in the loop definition, but overuse of multi-level breaks can make code harder to follow.

Code Breakdown

11
break immediately stops the loop. The numbers 6 through 10 will never be checked.
24
break 2 exits the inner loop AND the outer loop. Execution jumps to line 28.