Loop Control — break, continue, and Nested Loops
Control loop execution with break (exit early) and continue (skip to next iteration). Understand how they interact with nested loops and how to target specific loop levels.
Sometimes you need to exit a loop early when a condition is met (break), or skip the rest of the current iteration and jump to the next one (continue). Both work with for, while, and until loops.
break — Exit the Loop
# Find first matching file and stop
for file in *.log; do
if grep -q "CRITICAL" "$file"; then
echo "Found CRITICAL in: $file"
break # stop searching after first match
fi
done
# Infinite loop with break condition
while true; do
read -rp "Enter 'quit' to exit: " input
if [[ "$input" == "quit" ]]; then
echo "Goodbye!"
break
fi
echo "You said: $input"
donecontinue — Skip to Next Iteration
# Process only .sh files that start with "deploy"
for file in *.sh; do
if [[ "$file" != deploy* ]]; then
continue # skip non-deploy scripts
fi
echo "Deploying: $file"
bash "$file"
done
# Skip blank lines and comment lines when processing config
while IFS= read -r line; do
[[ -z "$line" ]] && continue # skip blank
[[ "$line" == "#"* ]] && continue # skip comments
echo "Config: $line"
done < config.txtNested Loops — Targeting Levels
break and continue with a numeric argument target outer loop levels. break 2 breaks out of two loop levels at once.
# Nested loop — break/continue target the innermost by default
for i in 1 2 3; do
for j in a b c; do
if [[ "$j" == "b" ]]; then
break # breaks inner loop only
fi
echo "$i-$j"
done
echo "Back in outer loop: i=$i"
done
# 1-a (then break inner), 2-a (then break inner), 3-a (then break inner)
# break 2 — exits both loops
found=""
for server in web1 web2 db1; do
for port in 80 443 8080; do
if nc -z "$server" "$port" 2>/dev/null; then
found="$server:$port"
break 2 # exit both for loops immediately
fi
done
done
echo "First open: $found"continue N
continue 2 skips to the next iteration of the outer loop. Like break N, it counts loop levels from the inside out.
select — Interactive Menu Loop
Bash's built-in select loop automatically builds a numbered menu and loops until you break:
PS3="Choose an option: " # the prompt for select
select option in "List files" "Check disk" "Exit"; do
case "$option" in
"List files")
ls -la
;;
"Check disk")
df -h
;;
"Exit")
echo "Bye!"
break
;;
*)
echo "Invalid choice: $REPLY"
;;
esac
doneIn a three-level nested loop, what does `break 2` do?
Write a script that:
- Loops from 1 to 20
- Skips even numbers (use
continue) - Prints "found 13!" and stops when it reaches 13 (use
break) - For all other odd numbers, prints the number