break / continue
| Since: | POSIX(sh互換) |
|---|
In shell scripts, break and continue are built-in commands that control the flow of loops. break immediately exits the current loop, while continue skips the remaining processing and advances to the next iteration. Both work with for, while, and until loops. Specifying a number with break n or continue n lets you directly control an outer loop in a nested structure.
Basic Syntax
break and continue used without arguments affect the current loop. Specifying a number n affects the n-th outer loop (innermost is 1).
| Syntax | Meaning | Description |
|---|---|---|
break | Exit loop | Immediately terminates the current loop. Execution continues from after done. |
break n | Exit n levels up | Terminates the n-th loop counting outward from the innermost. Default for n is 1. |
continue | Skip to next iteration | Skips subsequent processing and advances to the next condition evaluation or element. |
continue n | Next iteration of n-th outer loop | Advances to the next iteration of the n-th loop counting outward. |
# Basic form of break
for var in list; do
if exit_condition; then
break # <- exit the loop here
fi
processing
done
# Basic form of continue
for var in list; do
if skip_condition; then
continue # <- jump to the next iteration
fi
processing
done
# Use break 2 to exit the outer loop of a nested structure
for outer_var in list; do
for inner_var in list; do
if condition; then
break 2 # <- exits both loops
fi
done
done
# Use continue 2 to advance to the next iteration of the outer loop
for outer_var in list; do
for inner_var in list; do
if condition; then
continue 2 # <- advances to the next element of the outer loop
fi
done
done
break
Stops the loop when a condition is met. Commonly used when scanning a list from the beginning and immediately stopping once the target element is found. After break, execution moves to the code after the loop's done.
| Common Pattern | Description |
|---|---|
| Linear search (stop when found) | Scan an array from the beginning and use break to stop the remaining scan once a matching element is found. |
| Input validation loop | Loop with while true and use break to exit when valid input is received. |
| Abort on error detection | Interrupt the loop when unexpected content is detected while processing files or data. |
continue
Used when you want to skip specific elements and continue processing the rest. Well-suited for filtering operations or batch processing where you skip only the elements with errors and move on.
| Common Pattern | Description |
|---|---|
| Flag-based filtering | Use continue to skip elements whose status flag does not meet the condition, processing only valid elements. |
| Skipping blank lines and comments | When reading a file line by line, use continue to skip blank lines and lines starting with #. |
| Conditional aggregation | Use continue to exclude non-target elements when you only want to count or sum certain elements. |
break n / continue n (Nested Loop Control)
When loops are nested two or more levels deep, outer loops can be controlled directly without using flag variables. n is counted starting from 1 for the innermost loop and going outward. To exit the outermost loop in a 3-level nest, specify break 3.
| Syntax | How n is counted | Description |
|---|---|---|
break 1 | Innermost loop (same as break) | Exits the current loop. |
break 2 | One loop out | Exits both the inner loop and the outer loop. |
continue 2 | One loop out | Exits the inner loop and advances to the next iteration of the outer loop. |
Sample Code
dragonball_break.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates break (loop exit)
# using Dragon Ball characters
# -----------------------------------------------
# -----------------------------------------------
# Store character names and power levels in arrays
# -----------------------------------------------
names=("Goku" "Vegeta" "Piccolo" "Krillin" "Frieza")
powers=(9000 8500 3500 1750 530000)
# Power level threshold (stop searching when a character at or above this is found)
threshold=10000
echo "=== Searching from the top for a character with power >= ${threshold} ==="
echo ""
found_name=""
found_power=0
for ((i=0; i<${#names[@]}; i++)); do
name="${names[$i]}"
power="${powers[$i]}"
echo " Checking: ${name} (power: ${power})"
# break when a character with power at or above the threshold is found
if [ "${power}" -ge "${threshold}" ]; then
echo " -> ${name}'s power exceeds the threshold. Stopping search."
found_name="${name}"
found_power="${power}"
break
fi
done
echo ""
if [ -n "${found_name}" ]; then
echo "Found: ${found_name} (power: ${found_power})"
else
echo "No character with power >= ${threshold} was found."
fi
chmod +x dragonball_break.sh ./dragonball_break.sh === Searching from the top for a character with power >= 10000 === Checking: Goku (power: 9000) Checking: Vegeta (power: 8500) Checking: Piccolo (power: 3500) Checking: Krillin (power: 1750) Checking: Frieza (power: 530000) -> Frieza's power exceeds the threshold. Stopping search. Found: Frieza (power: 530000)
dragonball_continue.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates continue (skip to next iteration)
# using Dragon Ball characters
# -----------------------------------------------
# -----------------------------------------------
# Store character names and availability flags in arrays
# (1: available, 0: injured)
# -----------------------------------------------
names=("Goku" "Vegeta" "Piccolo" "Krillin" "Frieza")
active=(0 1 1 0 1)
echo "=== Display only available characters ==="
echo ""
active_count=0
for ((i=0; i<${#names[@]}; i++)); do
name="${names[$i]}"
flag="${active[$i]}"
# Skip with continue if the flag is 0 (injured)
if [ "${flag}" -eq 0 ]; then
echo " ${name}: injured, skipping"
continue
fi
# Only reaches here when the flag is 1 (available)
active_count=$((active_count + 1))
echo " ${name}: ready to deploy"
done
echo ""
echo "Available: ${active_count} fighters"
echo ""
echo "=== Sum only characters with power below 5000 ==="
echo ""
powers=(9000 8500 3500 1750 530000)
total=0
for ((i=0; i<${#names[@]}; i++)); do
power="${powers[$i]}"
# Skip with continue for characters with power >= 5000 (not included in sum)
if [ "${power}" -ge 5000 ]; then
echo " ${names[$i]} (${power}): out of scope, skipping"
continue
fi
total=$((total + power))
echo " ${names[$i]} (${power}): adding to total"
done
echo ""
echo "Total power of fighters below 5000: ${total}"
chmod +x dragonball_continue.sh ./dragonball_continue.sh === Display only available characters === Goku: injured, skipping Vegeta: ready to deploy Piccolo: ready to deploy Krillin: injured, skipping Frieza: ready to deploy Available: 3 fighters === Sum only characters with power below 5000 === Goku (9000): out of scope, skipping Vegeta (8500): out of scope, skipping Piccolo (3500): adding to total Krillin (1750): adding to total Frieza (530000): out of scope, skipping Total power of fighters below 5000: 5250
dragonball_break_n.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates break n (exiting nested loops)
# using Dragon Ball characters
# -----------------------------------------------
# -----------------------------------------------
# A double loop over stages x characters:
# when a specific combination is found, exit both loops
# -----------------------------------------------
stages=("Stage 1" "Stage 2" "Stage 3")
names=("Goku" "Vegeta" "Piccolo" "Krillin" "Frieza")
# When this combination is found, immediately end the entire search
target_stage="Stage 2"
target_name="Piccolo"
echo "=== Searching stage x character combinations ==="
echo "Target: ${target_stage} x ${target_name}"
echo ""
found=0
# Outer loop: iterate over stages
for stage in "${stages[@]}"; do
echo " [${stage}] start"
# Inner loop: iterate over characters
for name in "${names[@]}"; do
echo " Checking: ${name}"
# If target combination matches, use break 2 to exit both loops
if [ "${stage}" = "${target_stage}" ] && [ "${name}" = "${target_name}" ]; then
echo " -> Found: ${stage} x ${name}! Exiting both loops."
found=1
break 2
fi
done
echo " [${stage}] end"
done
echo ""
if [ "${found}" -eq 1 ]; then
echo "Search complete: found ${target_stage} x ${target_name}."
else
echo "Target combination was not found."
fi
chmod +x dragonball_break_n.sh
./dragonball_break_n.sh
=== Searching stage x character combinations ===
Target: Stage 2 x Piccolo
[Stage 1] start
Checking: Goku
Checking: Vegeta
Checking: Piccolo
Checking: Krillin
Checking: Frieza
[Stage 1] end
[Stage 2] start
Checking: Goku
Checking: Vegeta
Checking: Piccolo
-> Found: Stage 2 x Piccolo! Exiting both loops.
Search complete: found Stage 2 x Piccolo.
dragonball_continue_n.sh
#!/bin/bash
# -----------------------------------------------
# Demonstrates continue n (skip to next iteration
# of an outer loop) using Dragon Ball characters
# -----------------------------------------------
# -----------------------------------------------
# A double loop over stages x characters:
# when a banned character appears in the inner loop,
# skip to the next stage in the outer loop
# -----------------------------------------------
stages=("Stage 1" "Stage 2" "Stage 3")
names=("Goku" "Vegeta" "Piccolo" "Krillin" "Frieza")
# When this character appears, cut the current stage short and move to the next
banned="Frieza"
echo "=== Stage processing (move to next stage when ${banned} appears) ==="
echo ""
# Outer loop: iterate over stages
for stage in "${stages[@]}"; do
echo " [${stage}] start"
# Inner loop: iterate over characters
for name in "${names[@]}"; do
# If the banned character is found, use continue 2 to advance to the outer loop's next iteration
if [ "${name}" = "${banned}" ]; then
echo " ${name} detected -> skipping rest of ${stage} and moving to next stage"
continue 2
fi
echo " Processing: ${name}"
done
# This line is not reached when skipped by continue 2
echo " [${stage}] all characters processed"
done
echo ""
echo "=== All stages complete ==="
chmod +x dragonball_continue_n.sh
./dragonball_continue_n.sh
=== Stage processing (move to next stage when Frieza appears) ===
[Stage 1] start
Processing: Goku
Processing: Vegeta
Processing: Piccolo
Processing: Krillin
Frieza detected -> skipping rest of Stage 1 and moving to next stage
[Stage 2] start
Processing: Goku
Processing: Vegeta
Processing: Piccolo
Processing: Krillin
Frieza detected -> skipping rest of Stage 2 and moving to next stage
[Stage 3] start
Processing: Goku
Processing: Vegeta
Processing: Piccolo
Processing: Krillin
Frieza detected -> skipping rest of Stage 3 and moving to next stage
=== All stages complete ===
Notes
In shell scripts, break immediately exits a loop, and continue skips the remaining processing and advances to the next iteration. Both work with all loop constructs: for, while, and until. Specifying a number with break n or continue n lets you directly control a nested outer loop without using flag variables (counted starting from 1 for the innermost loop, going outward). This makes code more concise compared to flag-based control, but readability decreases as n grows larger — in practice, break 2 or continue 2 is about the upper limit. See also for loops and while / until for loop combinations.
If you find any errors or copyright issues, please contact us.