Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Loops and Functions  ›  Lesson

break and continue

break, continue 10 minInside a loop, continue skips the rest of the current pass and moves to the next one, while break leaves the loop entirely.

break and continue

One folder in the list was deleted last month, and backup.sh stops dead on it. Another day the backup disk fills up halfway through and every remaining tar fails, one error after another. Loops need two exits: skip this one and stop entirely.

The rule

continue skips to the next pass; break leaves the loop.

for dir in "${dirs[@]}"; do
    if [[ ! -d "$dir" ]]; then
        echo "Skipping missing folder: $dir" >&2
        continue                     # next folder, please
    fi
    if (( free_mb < 1024 )); then
        echo "Disk nearly full, stopping" >&2
        break                        # out of the loop entirely
    fi
    tar -czf "$dest/${dir##*/}.tar.gz" "$dir"
done
echo "Loop finished"                 # break lands here
  • continue abandons the rest of this pass. The loop goes on with the next item (or, in a while, the next test).
  • break abandons the whole loop. Execution resumes at the first line after done.
  • Both accept a number for nested loops: break 2 leaves two levels at once, and continue 2 jumps to the next pass of the outer loop.

The shortcut

Draw an arrow from the keyword. continue points up to the top of the loop, to the next item. break points down, past done. Everything between the keyword and the end of the body is skipped either way.

for i in 1 2 3 4 5 with a skip at 3Step 1 of 4
  1. Passes 1 and 2

    (( i == 3 )) fails, so echo "$i" runs: prints 1, then 2.

The while trap: if the counter is updated at the bottom of the body, a continue above it skips the update, and the loop repeats the same value forever. Update the counter before any continue.

Drills

Answer fast — trust the rule.

quick drill

What does for i in 1 2 3 4 5; do (( i == 3 )) && continue; echo -n "$i "; done print?

quick drill

The same loop with break instead of continue. What prints?

quick drill

Inside a loop nested in another loop, what does break 2 do?

quick drill

A while (( i < 5 )) loop has continue near the top and (( i++ )) at the bottom. When continue runs, what happens?

Remember

  • continue skips to the next pass; break leaves the loop.
  • Arrows: continue points up, break points down past done.
  • break 2 leaves two loops; update counters before any continue.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainSkip the missing, stop when full

In backup.sh's folder loop, skip any folder that does not exist (with a warning), and stop the whole loop if the backup disk has less than 1 GB free, held in a variable free_mb. Write the two lines inside the loop and explain what each keyword does and where execution goes next.