Loop Control with break and continue

Loop Control with break and continue in Bash: --- Picture the housekeeping supervisor at a large hotel starting the morning shift.


The Analogy: The Hotel Housekeeping Floor Supervisor

Picture the housekeeping supervisor at a large hotel starting the morning shift. She has a clipboard listing every floor in the building, and for each floor a list of rooms to service. Her job is a loop inside a loop: for each floor, walk the corridor and, for each room on that floor, do the standard turnover -- strip the beds, restock, clean, tick the room off. When she finishes a floor she moves to the next one. This is exactly a nested for loop: the outer loop steps through floors, the inner loop steps through rooms.

Most rooms are handled by simply falling through the checklist to the end and moving to the next door. But two special instructions change the flow, and they are the whole subject of this lesson. The first is a "Do Not Disturb" sign: when the supervisor sees one, she does not clean that room, she does not linger, she simply moves straight on to the next door. She skips the rest of the work for this one room and continues the corridor. That instruction is continue: abandon the current iteration, jump to the top of the loop, take the next item.

The second instruction is more drastic. Suppose she opens a room and finds a burst pipe flooding the floor. There is no point finishing the remaining rooms on this corridor; the whole floor is out of service. She stops the corridor walk immediately and leaves the floor. That is break: abandon the loop entirely and carry on with whatever comes after it. And if the fire alarm sounds, she does not just leave the current floor, she leaves the building -- every loop, inner and outer, stops at once. Bash expresses that with a count: break 2 breaks out of two enclosing loops, not just the innermost.

The subtle danger, and the source of most real bugs, is ambiguity about which loop an instruction targets. If the supervisor radios "stop" without saying stop-the-room, stop-the-floor, or stop-the-building, the message is useless. Bash has the same trap: a plain break always means the innermost loop only, so a programmer who mentally pictures "stop everything" while standing inside a nested loop will be surprised when the outer loop keeps going. The failure mode is not a crash; it is the loop quietly doing less, or more, than intended, and the output looking almost right. That is why every multi-level break deserves a comment naming exactly which loop it leaves.


Syntax or Core Structure

break and continue are loop-control keywords. continue ends the current iteration and starts the next one; break ends the loop altogether. Both work identically in for, while, until, and select loops. Here is a single loop that uses both: it processes odd numbers, skips even ones with continue, and stops entirely when it reaches four with break.

#!/usr/bin/env bash
for n in 1 2 3 4 5 6; do
  if (( n == 4 )); then
    echo "hit 4 -- stopping"
    break
  fi
  if (( n % 2 == 0 )); then
    echo "skip even $n"
    continue
  fi
  echo "process $n"
done
echo "loop done"

Output:

process 1
skip even 2
process 3
hit 4 -- stopping
loop done

Trace the flow. At n=1 neither guard fires, so it prints process 1. At n=2 the even test is true, so continue jumps back to the top without printing anything else for that number. At n=3 it prints process 3. At n=4 the first guard fires, prints the stop message, and break leaves the loop -- so 5 and 6 are never examined. Execution resumes at echo "loop done", which is the first statement after the loop body. The key observation is that continue keeps the loop alive while break ends it, and both skip whatever loop-body code sits below them.


Technical Depth: Levels, Nesting, and the Subshell Trap

The four control keywords at a glance

Bash gives you two keywords and an optional numeric argument on each. The number counts enclosing loops from the inside out: level 1 is the loop you are standing in, level 2 is the loop around that, and so on. A bare break is identical to break 1.

KeywordWith no countWith count NEffect
continuerestart innermost loopcontinue Njump to the next iteration of the Nth enclosing loop
breakexit innermost loopbreak Nexit N enclosing loops at once
break 1same as break--exit only the current loop
break 2--exit two levelsleave both the inner and the outer loop

Leaving two loops at once with break 2

A common pattern is scanning a grid for the first cell that matches a condition. Once found, there is no reason to keep scanning either dimension. A bare break would only leave the inner loop and the outer loop would start the next row; break 2 leaves both.

#!/usr/bin/env bash
target=5
for r in 1 2 3; do
  for c in 1 2 3; do
    sum=$(( r + c ))
    if (( sum == target )); then
      echo "found at r=$r c=$c (sum $sum)"
      break 2
    fi
    echo "check r=$r c=$c sum=$sum"
  done
done
echo "scan finished"

Output:

check r=1 c=1 sum=2
check r=1 c=2 sum=3
check r=1 c=3 sum=4
check r=2 c=1 sum=3
check r=2 c=2 sum=4
found at r=2 c=3 (sum 5)
scan finished

The scan walks row 1 fully (sums 2, 3, 4), then row 2. At r=2 c=3 the sum reaches the target of 5, so it prints the found message and break 2 exits both loops in one step. Nothing from row 3 is examined, and control jumps straight to scan finished. Had this been a plain break, the outer loop would have advanced to r=3 and kept scanning -- a classic off-by-one-loop bug.

Skipping an outer iteration with continue 2

The mirror image of break 2 is continue 2: abandon the current inner iteration and jump to the next iteration of the outer loop. This is how you say "this whole batch is spoiled, move to the next batch" from inside the inner loop.

#!/usr/bin/env bash
for batch in A B C; do
  echo "open batch $batch"
  for item in 1 2 3; do
    if [[ $batch == B && $item -eq 2 ]]; then
      echo "  batch $batch item $item BAD -- abandon batch"
      continue 2
    fi
    echo "  batch $batch item $item ok"
  done
  echo "close batch $batch"
done
echo "all batches attempted"

Output:

open batch A
  batch A item 1 ok
  batch A item 2 ok
  batch A item 3 ok
close batch A
open batch B
  batch B item 1 ok
  batch B item 2 BAD -- abandon batch
open batch C
  batch C item 1 ok
  batch C item 2 ok
  batch C item 3 ok
close batch C
all batches attempted

Batch A runs all three items and reaches close batch A. In batch B, item 2 triggers continue 2, which skips the rest of B's items and, crucially, skips the close batch B line too -- it jumps straight to the outer loop's next value, batch C. Notice what that means: the "close" line only prints for batches that finish cleanly, which is often exactly the semantics you want for a commit-or-rollback pattern.

The retry loop: break on success

Loop control is not only about nested loops. A very common single-loop idiom is bounded retry: attempt something up to N times, and break the moment it succeeds so you do not waste the remaining attempts.

#!/usr/bin/env bash
attempt=0
max=3
while (( attempt < max )); do
  attempt=$(( attempt + 1 ))
  if (( attempt == 2 )); then
    echo "attempt $attempt: success"
    break
  fi
  echo "attempt $attempt: failed, will retry"
done
echo "finished after $attempt attempt(s)"

Output:

attempt 1: failed, will retry
attempt 2: success
finished after 2 attempt(s)

Attempt 1 fails and falls through to the bottom of the loop, so the while test runs again. Attempt 2 succeeds, prints its message, and break leaves the loop before a third attempt is ever made. The counter is incremented at the top, before the work, which guarantees forward progress -- a detail that matters enormously, because a continue placed above the increment would loop forever. That specific hazard is covered in Common Mistakes.


Real World Example: A Multi-Host Preflight Checklist

Deployment tooling often runs a checklist against a set of hosts before shipping: disk space, open ports, certificate validity. The reaction to a failure depends on its severity. A warning is noted and the host keeps going. A critical failure abandons that one host but lets the others proceed -- continue 2. A blocker means the whole environment is unsafe and the entire run aborts -- break 2. This program encodes the checklist as data and drives all three reactions from it.

#!/usr/bin/env bash
set -u

# checklist rows: host check severity result
# severity: warn | critical | blocker ; result: pass | fail
read -r -d '' DATA <<'ROWS'
web1 disk ok pass
web1 ports critical pass
web1 certs warn pass
web2 disk ok pass
web2 ports critical fail
web2 certs warn pass
db1 disk ok pass
db1 replication blocker fail
db1 ports critical pass
ROWS

hosts_done=0
passed=0
run_aborted=0

for host in web1 web2 db1; do
  echo "== host $host =="
  while read -r h check sev res; do
    [[ $h == "$host" ]] || continue
    if [[ $res == pass ]]; then
      echo "  $check: pass"
      passed=$(( passed + 1 ))
      continue
    fi
    case $sev in
      warn)
        echo "  $check: FAIL (warn) -- noting and moving on"
        ;;
      critical)
        echo "  $check: FAIL (critical) -- abandoning host $host"
        continue 2
        ;;
      blocker)
        echo "  $check: FAIL (blocker) -- aborting entire run"
        run_aborted=1
        break 2
        ;;
    esac
  done <<< "$DATA"
  echo "  host $host: all checks complete"
  hosts_done=$(( hosts_done + 1 ))
done

echo "---"
echo "hosts fully cleared: $hosts_done"
echo "checks passed: $passed"
echo "run aborted: $run_aborted"

Output:

== host web1 ==
  disk: pass
  ports: pass
  certs: pass
  host web1: all checks complete
== host web2 ==
  disk: pass
  ports: FAIL (critical) -- abandoning host web2
== host db1 ==
  disk: pass
  replication: FAIL (blocker) -- aborting entire run
---
hosts fully cleared: 1
checks passed: 5
run aborted: 1

Follow the three reactions. Host web1 passes all three checks and reaches all checks complete, so hosts_done becomes 1. Host web2 passes disk, then hits a critical ports failure: continue 2 abandons web2 and jumps to the outer loop's next host, so web2 never prints its "complete" line and never increments the counter. Host db1 passes disk, then hits a blocker on replication: break 2 exits both loops immediately, so db1's remaining ports row is never even read, and the summary prints.

The inner while reads the whole checklist each time and filters to the current host with the guard [[ $h == "$host" ]] || continue. That guard is itself a nice use of continue: it skips rows belonging to other hosts without any nested if. Because the loop reads from a here-string with <<<, not from a pipe, the counters it increments survive after the loop -- a subtlety the Common Mistakes section returns to, since the same code written with a pipe would silently report zero.

This works, but it has real defects worth stating plainly. First, the summary is misleading: checks passed: 5 counts the disk checks on web2 and db1 even though those hosts were abandoned and never cleared, so a reader sees "5 passed, 1 host cleared" and cannot reconcile the two numbers -- the count should be scoped per host or discarded when a host is abandoned. Second, re-reading and re-filtering the full DATA block once per host is O(hosts times checks); a real tool would group rows by host once. Third, the break 2 and continue 2 counts are hard-wired to the current nesting: if someone later wraps the inner while in another loop, both numbers become silently wrong, which is exactly the fragility that makes many teams prefer refactoring the inner loop into a function that returns a status instead of using multi-level breaks.


Common Mistakes

  1. Assuming a bare break exits all nested loops. break leaves only the innermost loop; the loop around it continues with its next iteration. If you mean to leave two levels you must write break 2. This is the single most common loop-control bug, and it produces output that looks almost right because the outer loop simply does one more pass than intended.
  1. break or continue inside a piped while read. printf '%s' ... | while read ... runs the loop in a subshell, so break only leaves the subshell and, worse, any variable the loop set is lost when the subshell exits. A counter incremented inside such a loop reads as zero afterward. Use a here-string (<<<) or process substitution (< <(cmd)) so the loop runs in the current shell.
  1. continue placed before the counter increment. In a while loop that advances a counter in its body, a continue above the increment skips the increment, the loop condition never changes, and the script hangs forever. Always increment before any continue, or use a for (( )) loop whose step runs automatically.
  1. Confusing continue N with break N. continue 2 jumps to the next iteration of the second loop; break 2 exits the second loop entirely. They read similarly but behave very differently -- one keeps the outer loop alive, the other kills it. Mixing them up abandons too much or too little work.
  1. Using break or continue outside any loop. A break in the middle of a plain script, or inside a function but not inside a loop, is not fatal in Bash: it prints "only meaningful in a loop" to standard error and execution simply carries on. The bug is silent in the sense that the script does not stop, so the intended control flow never happens.
  1. A break count larger than the nesting depth. break 3 when only two loops enclose the statement does not error; Bash breaks out of every loop it can, which is two. Code that later loses a loop level keeps the break 3 and now over-breaks. Keep the count equal to the real depth and comment it.
  1. Expecting code after break to still run. Statements in the loop body below a break on the path that took the break are skipped -- break transfers control to the first statement after the loop, not to the rest of the body. Cleanup that must always happen belongs after the loop or in a trap, not below the break.
  1. Confusing exit with break. exit terminates the whole script (or the current subshell), not just the loop. Reaching for exit when you meant break can tear down a script that was only supposed to stop iterating, taking any post-loop reporting down with it.
  1. Relying on break under set -e when a command fails. Under set -e, a command in the loop body that returns non-zero aborts the script before your break or continue is ever reached. If you want to react to a failure with loop control, test it explicitly with an if or || rather than letting errexit fire first.

Best Practices

  • Comment every multi-level break or continue. Write a short note naming which loop break 2 leaves. The count is invisible to a reader who cannot see the loop boundaries at a glance, and the comment survives refactors as a check on whether the count is still right.
  • Prefer a here-string or process substitution over a pipe for while read loops. while read ...; done <<< "$data" and done < <(cmd) both run in the current shell, so break, continue, and any variables the loop sets behave as written. A pipe silently pushes the loop into a subshell.
  • Increment loop counters before any continue. Guarantee forward progress by advancing the counter at the top of a while body, above every continue. Better still, use for (( i=0; i<n; i++ )), whose step clause runs no matter how the body exits its iteration.
  • Refactor deep nesting into a function that returns instead of using break 3+. When you find yourself reaching for break 3, the inner loops are usually a self-contained search. Extract them into a function and return the result; return from a function is clearer and immune to nesting-depth drift.
  • Use continue to flatten guard conditions. A leading [[ condition ]] || continue at the top of a loop body skips irrelevant items without wrapping the rest of the body in a nested if. It reads as an early-out and keeps the main logic at one indentation level.
  • Keep loop bodies short enough to see both ends. break and continue are readable only when the loop they control fits on screen. If the body is long, the reader cannot tell which loop a break leaves; shortening the body or extracting a function restores that clarity.
  • Test loop control with data that exercises every branch. Include inputs that trigger the skip path, the break path, and the fall-through path. Loop-control bugs hide on the branch your sample data never reaches, so a test that only ever falls through proves nothing about the break.
  • Do not lean on break to escape a failing command under set -e. Make failure reactions explicit with if or || so errexit does not abort the script before the loop-control keyword runs. This keeps the intended flow visible and independent of the shell's error mode.

Practice Exercises

  1. Replace a flag with break. Take a loop that sets a found=1 variable and keeps iterating to the end, then tests the flag afterward. Rewrite it to break the moment the item is found, and confirm the output is identical while fewer iterations run. Add an echo inside the loop to prove the later items are no longer examined.
  1. Grid search with break 2. Write a nested loop over a 4-by-4 grid of coordinates that stops at the first cell whose row plus column equals a target you set. Print each cell you check and the cell you find, and use break 2 so no cell past the match is examined. Then change it to a bare break and observe how many extra cells get checked.
  1. Demonstrate the subshell trap. Write the same counting loop twice: once as printf ... | while read and once as while read ... done <<< "$data". Print the counter after each. Explain in a comment why the piped version prints zero and the here-string version prints the true count.
  1. Severity-driven batch processor. Build a loop over several batches, each with several items, where an item can be ok, skippable, or fatal. Use continue to skip a single bad item, continue 2 to abandon a whole batch, and break 2 to abort everything on a fatal item. Drive it from a data block and verify each reaction fires on the right input.