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
continueskips to the next pass;breakleaves 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 herecontinueabandons the rest of this pass. The loop goes on with the next item (or, in awhile, the next test).breakabandons the whole loop. Execution resumes at the first line afterdone.- Both accept a number for nested loops:
break 2leaves two levels at once, andcontinue 2jumps 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.
Passes 1 and 2
(( i == 3 ))fails, soecho "$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.
What does for i in 1 2 3 4 5; do (( i == 3 )) && continue; echo -n "$i "; done print?
The same loop with break instead of continue. What prints?
Inside a loop nested in another loop, what does break 2 do?
A while (( i < 5 )) loop has continue near the top and (( i++ )) at the bottom. When continue runs, what happens?
Remember
continueskips to the next pass;breakleaves the loop.- Arrows: continue points up, break points down past
done. break 2leaves two loops; update counters before anycontinue.
