break
Exit prematurely from loop structures
TLDR
Break out of a single loop
Break out of nested loops
SYNOPSIS
break [n]
PARAMETERS
n
An optional integer specifying the number of nested loops to exit. If n is 1, it exits the current (innermost) loop. If n is greater than 1, it exits n levels of enclosing loops. If n is not provided, it defaults to 1.
DESCRIPTION
The break command is a shell built-in used to exit immediately from for, while, until, or select loops within a shell script or interactive shell session. When break is executed, the remaining commands in the current loop iteration are skipped, and the loop itself is terminated. Execution then continues with the command immediately following the loop. By default, break exits only the innermost loop. However, it can be provided with an integer argument to specify how many levels of nested loops to exit simultaneously. This command is crucial for controlling flow in shell scripts, allowing for early termination of loops based on specific conditions, improving efficiency and logic.
CAVEATS
break is a shell built-in command, not an external executable. It is interpreted directly by the shell.
It can only be used within the context of for, while, until, or select loops. Using it outside these constructs will result in an error.
It does not affect if statements or case statements; its scope is strictly limited to loop constructs.
USAGE EXAMPLE
Here's a simple example demonstrating the use of break:
#!/bin/bash
for i in {1..10}; do
if [ $i -eq 5 ]; then
echo "Breaking loop at i = $i"
break
fi
echo "Current i = $i"
done
echo "Loop finished."
This script will print 'Current i = 1' through 'Current i = 4', then 'Breaking loop at i = 5', and finally 'Loop finished.', as the loop terminates when i reaches 5.
For nested loops:
#!/bin/bash
for i in {1..3}; do
echo "Outer loop i = $i"
for j in {1..3}; do
if [ $i -eq 2 ] && [ $j -eq 2 ]; then
echo "Breaking 2 levels at i = $i, j = $j"
break 2
fi
echo " Inner loop j = $j"
done
done
echo "Script finished."
This will exit both loops when i is 2 and j is 2, printing 'Script finished.' immediately after.
HISTORY
The break command has been a fundamental control flow mechanism in Unix shells since the original Bourne shell (sh). Its functionality has remained consistent across subsequent shell implementations like the KornShell (ksh) and Bash (bash), serving as a core component for structured programming in shell scripts. Its simple yet powerful ability to prematurely exit loops makes it an indispensable tool for scriptwriters, adapting to evolving scripting needs without significant changes to its core behavior.