break
Quick Reference
Command Name:
break
Category:
shell builtins
Platform:
Linux/Unix
Basic Usage:
Common Use Cases
- 1
Loop control
Exit from loops when certain conditions are met
- 2
Error handling
Stop loop execution when an error occurs to prevent further processing
- 3
Nested loop management
Exit from multiple levels of nested loops with a single command
- 4
Interactive menus
Provide exit functionality in interactive shell script menus
Syntax
break [n]
Options
Option | Description |
---|---|
n |
Optional integer argument that specifies how many nested loops to exit from. Default is 1, meaning it exits only the innermost loop. |
Examples
How to Use These Examples
The examples below show common ways to use the break
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
Basic Examples:
# Simple break to exit a loop for i in 1 2 3 4 5; do echo $i if [ $i -eq 3 ]; then break fi done echo "Loop exited"
Advanced Examples:
# Break with numeric argument to exit multiple nested loops for i in 1 2 3; do echo "Outer loop: $i" for j in a b c; do echo " Inner loop: $j" if [ $i -eq 2 ] && [ "$j" = "b" ]; then echo " Breaking out of both loops" break 2 fi done done echo "Both loops exited"