Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The break statement is a shell builtin command used to prematurely terminate the execution of an enclosing for, while, until, or select loop. When evaluated, it immediately halts the loop’s execution cycle and transfers control flow to the command immediately following the terminated loop structure.

Syntax

break [n]

Parameters

  • n (Optional): An integer literal (>= 1) specifying the number of nested loop levels to exit.
    • If omitted, n defaults to 1, terminating only the innermost enclosing loop.
    • If n is greater than the current depth of nested loops, break terminates all enclosing loops and transfers control to the statement following the outermost loop.

Execution Mechanics

  1. Scope: break only applies to loop constructs. It does not terminate functions, scripts, or subshells (which require return or exit). While frequently nested inside conditional statements (if or case), break ignores these structures when calculating the depth n and only counts the enclosing loops.
  2. Exit Status: The return status of the break command is 0 (success), unless the provided argument n is not an integer greater than or equal to 1.
  3. Control Transfer: Any commands remaining in the current loop iteration after the break statement are bypassed.

Syntax Visualization

Single Loop Termination (break or break 1)
for i in 1 2 3; do
    echo "Starting iteration $i"
    
    if [ "$i" -eq 2 ]; then
        break
    fi
    
    echo "Finishing iteration $i" # Bypassed when i=2
done
echo "Control flow resumes here immediately after break"
Nested Loop Termination (break n)
for outer_var in 1 2; do
    for inner_var in A B; do
        echo "Outer: $outer_var, Inner: $inner_var"
        
        if [ "$outer_var" -eq 1 ] && [ "$inner_var" = "A" ]; then
            break 2  # Terminates both the inner and outer loops
        fi
        
        echo "Inner loop continuation" # Bypassed when break 2 is evaluated
    done
    echo "Outer loop continuation" # Bypassed when break 2 is evaluated
done
echo "Control flow resumes here immediately after break 2"
Master Bash with Deep Grasping Methodology!Learn More