Skip to the workspace
Pebellslearn by building
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.

shell bash / break and continue

Explore each scene at your own pace.

01 · The rule

The rule

break and continue

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

Compare skipping one item with ending the entire traversal.

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.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.