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 positive integer; number of enclosing loop levels to exit (default: 1).

DESCRIPTION

The break command is a shell builtin used in Bash, sh, and other POSIX-compliant shells to terminate the execution of the nearest enclosing for, while, or until loop. It provides a way to exit loops early based on conditions, improving script efficiency and readability.

When invoked as break without arguments, it exits the innermost loop. An optional numeric argument n specifies the number of nested loop levels to break out of, defaulting to 1 if omitted. For instance, in a nested loop structure, break 2 exits two levels.

Example usage:
for i in {1..5}; do
  if [ $i -eq 3 ]; then
    break;
  fi
  echo "Number: $i";
done

This prints "Number: 1" and "Number: 2" before exiting.

Break is essential for implementing conditional exits, error handling, or timeouts in loops. It does not affect functions or scripts directly but only loops. Outside a loop context, it triggers an error like "break: only meaningful in a `for', `while', or `until' loop".

Common in automation scripts, it pairs with continue for fine-grained loop control, enabling complex logic without deep nesting or flags.

CAVEATS

Valid only inside for, while, or until loops; n must be ≥1 and ≤ nesting depth, else error. Non-interactive shells may behave differently.

EXAMPLE: NESTED LOOPS

for outer in 1 2; do
for inner in a b c; do
  if [ $inner = b ]; then break 2; fi
  echo "$outer-$inner";
done
done
Exits both loops at '1-b', printing only '1-a'.

ERROR CASE

break
Outside loop: bash: break: only meaningful in a `for', `while', or `until' loop

HISTORY

Originated in the Bourne shell (1977) by Stephen Bourne at Bell Labs; standardized in POSIX.1-1988 and evolved in shells like Bash (1989+).

SEE ALSO

continue (bash builtin), return (bash builtin), exit(3)

Copied to clipboard