Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Bash Syntax

Bash break and continue

Reference for the Bash break and continue builtins: leave a loop early, skip to the next iteration, exit several nested levels with a number and see their return status.

break and continue are shell builtins that change the flow of the innermost enclosing loop (for, while, until or select). break leaves the loop immediately; continue skips the rest of the current pass and starts the next one.

Both take an optional number n to act on the n-th enclosing loop, which is the shell's way of escaping nested loops without flags or goto.

Terminal
break [n]
continue [n]

Try it

Bash Skip and stop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash Nested loops and levels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
break [n]
continue [n]
Parameter Description
n Positive integer: how many enclosing loops to affect. Default 1. If n is larger than the nesting depth, the outermost loop is used.

Returns: 0, unless n is not a positive integer (an error message and a non-zero status). Used outside a loop, the builtin prints a warning and still returns 0.

Usage notes

  • They work inside if, case and braces within the loop, because those do not start a new loop level. They do not cross a function boundary reliably: a break inside a function called from a loop can break the caller's loop in Bash, but this is surprising and best avoided.
  • A subshell (parentheses, a pipeline stage or $( )) is a separate process. break in cmd | while ...; do ... done works inside the piped loop, but a break in ( ... ) cannot reach a loop outside.
  • In while read loops, continue re-runs the condition, so the next line is read normally. In C-style for ((...)), continue still runs the step expression.
  • break leaves the loop with the loop variable at its current value; it is not reset.
  • With select, break is the normal way out of the menu.
  • Use a found flag or a function with return when a loop has several exit conditions; break 2 is concise but hard to read beyond two levels.
  • Neither command exits the script: use exit or return for that.