LinuxCommandLibrary

break

Exit prematurely from loop structures

TLDR

Break out of a single loop

$ while :; do break; done
copy

Break out of nested loops
$ while :; do while :; do break 2; done; done
copy

SYNOPSIS

break [n]

PARAMETERS

n
    Optional. An integer specifying how many nested loops to break out of. Defaults to 1 if omitted.

DESCRIPTION

The break command in Linux is used to terminate the execution of loops (like for, while, and until) and case statements prematurely. When break is encountered within a loop, the loop's execution is halted, and control is transferred to the statement immediately following the loop. If break is used within nested loops, only the innermost loop containing the break statement is terminated. The break command is commonly used in shell scripts to exit loops based on specific conditions, making scripts more efficient by avoiding unnecessary iterations or to handle exceptional situations gracefully. It's a fundamental tool for controlling program flow in shell scripting and other programming contexts within a Linux environment. It can also be followed by an integer to break out of multiple nested loops.

CAVEATS

Using break outside of a loop or case statement results in an error. Using too large a number as an argument to 'break' will cause the break to 'break' out of the largest number of loops possible.

EXAMPLES

Example 1: Exiting a loop based on a condition:
for i in 1 2 3 4 5; do if [ $i -gt 3 ]; then break; fi; echo $i; done

Example 2: Breaking out of two nested loops:
for i in 1 2; do for j in a b; do if [ $i -eq 2 -a $j = 'b' ]; then break 2; fi; echo "i=$i, j=$j"; done; done

SEE ALSO

continue(1), exit(1)

Copied to clipboard