Break, Continue, and Early Exit Patterns
Break, Continue, and Early Exit Patterns
Controlling loop flow and establishing defensive guard clauses prevents deeply nested indentation.
# Guard clause pattern: validate early, exit early
process_file() {
local file="$1"
[[ -f "$file" ]] || return 1
[[ -r "$file" ]] || return 2
# Actual work continues un-indented
cat "$file"
}
# Multi-level break
for outer in {1..5}; do
for inner in {a..e}; do
if [[ $outer -eq 3 && $inner == "c" ]]; then
break 2 # Exits BOTH inner and outer loops
fi
done
done