break, continue and nested loops
break exits an enclosing loop and continues after it; it does not exit the whole script. continue skips the remainder of the current iteration and advances to the next condition or item. In arithmetic for loops it executes the update first. With nested loops, both commands act on the innermost loop by default. A positive argument such as break 2 exits two enclosing loops; continue 2 resumes the second enclosing loop at its next iteration. Use these forms only when the nesting is obvious. A search can stop at the first match; a filter can skip unwanted items. Update any while-loop counter before a possible continue, or place the update so every path progresses.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Skip and stop
for item in 1 2 3 4 5; do if [[ $item == 2 ]]; then continue; fi if [[ $item == 5 ]]; then break; fi printf '%s\n' "$item"doneprintf '%s\n' finishedExpected stdout:
134finished2 is skipped, 5 ends the loop, and the script continues.
Exit two loops
for row in A B; do for col in 1 2; do printf '%s%s\n' "$row" "$col" if [[ $col == 2 ]]; then break 2; fi donedoneprintf '%s\n' endExpected stdout:
A1A2endThe first matching inner iteration exits both loops.
Continue the outer loop
for row in A B; do for col in 1 2 3; do if [[ $col == 2 ]]; then continue 2; fi printf '%s%s\n' "$row" "$col" donedoneExpected stdout:
A1B1Column 2 advances the outer row, skipping column 3.
Common mistakes
break is not exit, and continue is not break. In a while loop a continue before the only counter update may prevent progress.
Practice
Print values 1 through 5 except 3; then stop before printing 5. Expected output: 1, 2, 4. In a separate two-level loop compare break and break 2.
Next: select and interactive menus