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
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.