break and continue
Normally a loop runs every iteration until its list is used up or its condition fails. The commands break and continue let the body of a loop change that course. break leaves the loop completely, and continue skips the rest of the current pass and moves on to the next one. They work in for, while and until loops (lessons 78 to 81) and make it possible to stop as soon as the answer is found or to ignore items that do not need processing.
break: Leave the Loop
for i in 1 2 3 4 5; do
[ "$i" -eq 3 ] && break
echo "i=$i"
done
echo "after loop i=$i"
Output:
i=1
i=2
after loop i=3
When i reaches 3, the test succeeds, the && runs break (lesson 65), and Bash jumps to the first command after done. The values 4 and 5 are never visited. The last line shows that the loop variable keeps the value it had when the loop was left.
continue: Skip to the Next Pass
for i in 1 2 3 4 5; do
[ "$i" -eq 3 ] && continue
echo "i=$i"
done
Output:
i=1
i=2
i=4
i=5
For i equal to 3 the continue command ended the current pass before the echo ran, and the loop went on with 4. Unlike break, the loop itself is not over.
The difference can be summed up in one line: break means "I am finished with the whole loop", while continue means "I am finished with this item".
Stopping When Something Is Found
The most common use of break is a search. Once you have found what you were looking for, there is no reason to examine the remaining items:
for f in alpha beta gamma delta; do
if [ "$f" = gamma ]; then echo "found $f"; break; fi
echo "checked $f"
done
Output:
checked alpha
checked beta
found gamma
The delta item was never checked. For long lists or slow checks, such as downloading something for each item, stopping early saves real time. The same pattern works when reading a file:
printf 'ana:1\nbob:2\ncy:3\n' > users.txt
while IFS=: read -r name id; do
if [ "$name" = bob ]; then echo "bob has id $id"; break; fi
done < users.txt
Output:
bob has id 2
The loop reads lines until it finds the one for bob. The IFS=: setting splits each line at the colon (lesson 80).
Skipping Items with continue
The usual use of continue is to filter out items you do not want. This loop reads a configuration file and ignores blank lines and comments:
printf '# comment\n\nkeep one\n # indented comment\nkeep two\n' > cfg.txt
while IFS= read -r line; do
case "$line" in ''|'#'*|*[[:space:]]'#'*) continue ;; esac
echo "setting: $line"
done < cfg.txt
Output:
setting: keep one
setting: keep two
The case statement (lessons 75 and 76) tests three patterns: an empty line, a line that starts with #, and a line whose # comes after a space or tab. If one of them matches, continue skips the echo. A guard like this keeps the main work of the loop at the same indentation level and avoids deeply nested if blocks.
The same idea handles missing files:
touch real.txt
for f in real.txt missing.txt; do
[ -e "$f" ] || { echo "skip $f"; continue; }
echo "processing $f"
done
Output:
processing real.txt
skip missing.txt
The braces group the echo and the continue, so that both run when the test fails.
continue in while Loops: Update the Counter First
In a for loop over a list, continue is always safe because the list moves forward by itself. In a while loop, the counter is changed by your code, and continue jumps over everything after it. If the update comes after the continue, the loop can get stuck. This loop is written correctly, with the update first:
i=0
while [ "$i" -lt 6 ]; do
i=$((i + 1))
(( i % 2 == 0 )) && continue
echo "odd: $i"
done
Output:
odd: 1
odd: 3
odd: 5
The counter is increased before continue can skip the rest, so every pass makes progress. Now compare this version, where the update comes last and the continue runs when i is 1. A guard counter has been added so that the demonstration stops:
i=0; guard=0
while [ "$i" -lt 3 ]; do
guard=$((guard + 1))
[ "$guard" -gt 5 ] && { echo "guard stopped it"; break; }
if [ "$i" -eq 1 ]; then continue; fi
i=$((i + 1))
done
echo "i=$i guard=$guard"
Output:
guard stopped it
i=1 guard=6
When i became 1, continue skipped the i=$((i + 1)) line, so i stayed 1 forever. Without the guard this loop would never end (lesson 87). Whenever you use continue in a while or until loop, make sure the code that moves the loop forward runs before it.
continue in C-Style for Loops
The C-style loop from lesson 79 has its update step in the loop header, which makes it safe. continue still runs the update expression before the next test:
for (( i = 0; i < 6; i++ )); do
(( i == 2 )) && continue
echo -n "$i "
done; echo
Output:
0 1 3 4 5
The value 2 was skipped, but i++ still ran, so the loop continued with 3.
Breaking Out of Several Loops
Both commands accept an optional number that says how many enclosing loops they apply to. The default is 1, the innermost loop. break 2 leaves the innermost loop and the loop around it:
for a in 1 2 3; do
for b in 1 2 3; do
if [ "$a" -eq 2 ] && [ "$b" -eq 2 ]; then break 2; fi
echo "a=$a b=$b"
done
done
echo "done"
Output:
a=1 b=1
a=1 b=2
a=1 b=3
a=2 b=1
done
At a=2 and b=2, break 2 ended both loops at once, so a=3 was never reached. With a plain break, only the inner loop would have ended and the outer loop would have gone on to a=3:
for a in 1 2 3; do
for b in 1 2 3; do
[ "$b" -eq 2 ] && break
echo "a=$a b=$b"
done
done
Output:
a=1 b=1
a=2 b=1
a=3 b=1
Each inner loop stopped at b=2, but the outer loop ran three times.
continue with a Number
continue 2 skips the rest of the current pass of the inner loop and of the outer loop's body, and starts the next pass of the outer loop:
for a in 1 2 3; do
for b in 1 2 3; do
[ "$b" -eq 2 ] && continue 2
echo "a=$a b=$b"
done
done
Output:
a=1 b=1
a=2 b=1
a=3 b=1
The output looks the same as the plain break version, because nothing follows the inner loop. The difference would show if the outer body had more commands after the inner loop: continue 2 would skip them, while a plain break would run them. Lesson 85 uses these numbers in nested loops.
Unusual Numbers
If you give a number larger than the number of enclosing loops, Bash simply leaves all of them:
for a in 1 2; do
for b in 1 2; do
break 5
done
echo "outer a=$a"
done
echo "after"
Output:
after
There are two loops, so break 5 ended both, and the echo "outer a=$a" line never ran. A number below 1 is an error. In Bash 5.2.21, break 0 printed an error message and the loop ended with status 1:
for a in 1; do break 0; echo "not reached"; done; echo "status: $?"
Output:
t84.sh: line 81: break: 0: loop count out of range
status: 1
The message begins with the name of the script and the line number, as the sandbox printed it for a script file. Typed interactively it begins with bash:.
Using break and continue Outside a Loop
They only make sense inside a loop. Elsewhere, Bash prints a warning and carries on with status 0:
break
echo "status: $?"
Output:
t84.sh: line 83: break: only meaningful in a `for', `while', or `until' loop
status: 0
The command continue behaves the same way. This often means a break was left behind after code was moved out of a loop. To leave a function, use return, not break.
break in a case Statement Inside a Loop
A case statement is not a loop, so a break inside it applies to the loop around it. This is the usual shape of a command loop that has a "quit" choice:
for cmd in start stop quit more; do
case "$cmd" in
quit) echo "quitting"; break ;;
*) echo "handling $cmd" ;;
esac
done
Output:
handling start
handling stop
quitting
The ;; still ends the quit clause, as in any case statement, even though the loop is left before it is reached. Lesson 86 uses the same structure for select menus.
Exit Status After break and continue
The status of a loop that ended with break is the status of the break command, which is 0:
for i in 1 2; do false; break; done
echo "status after break: $?"
for i in 1 2 3; do [ "$i" = 2 ] && break; done; echo "status: $?"
for i in 1 2 3; do true; done; echo "status: $?"
Output:
status after break: 0
status: 0
status: 0
The false before break did not matter. A loop left by break always reports success, so do not rely on the loop's status to learn whether the item was found. Set a variable before the break, or use a function with return, as shown next.
Returning from a Function Instead
When a loop is the main body of a function, return leaves the loop and the function in one step and carries a result:
find_first() {
local x
for x in "$@"; do [ "$x" -gt 10 ] && { echo "$x"; return 0; }; done
return 1
}
find_first 3 8 12 20; echo "status $?"
find_first 1 2; echo "status $?"
Output:
12
status 0
status 1
The function prints the first number greater than 10 and returns 0, or returns 1 if there is none. The status therefore does tell the caller whether the item was found. Lessons 88 to 92 cover functions and local.
break in a Loop at the End of a Pipe
A loop on the right-hand side of a pipe runs in a subshell, as lesson 83 explained. break still stops the loop correctly, but variables set inside it do not reach the main script:
n=0
printf 'a\nb\nc\nd\n' | while read -r l; do
n=$((n+1))
[ "$l" = c ] && break
echo "line $l"
done
echo "n outside pipe: $n"
Output:
line a
line b
n outside pipe: 0
The loop stopped at c, but n stayed 0 in the main shell. Use < <(command) or a redirection from a file when the main script needs the result.
break with an Intentional Infinite Loop
An infinite loop plus break is a standard way to express "keep going until something inside decides to stop":
n=0
while true; do
n=$((n + 1))
[ "$n" -ge 3 ] && break
done
echo "n=$n"
Output:
n=3
This form is useful when the exit test belongs in the middle of the body, not at the start. The next lessons on nested loops (85) and on infinite loops (87) build on it.
Portability
break, continue and their numeric forms are part of POSIX, so Dash handles them as Bash does:
#!/bin/sh
for a in 1 2 3; do
for b in 1 2 3; do
[ "$b" -eq 2 ] && continue 2
echo "a=$a b=$b"
done
done
for a in 1 2 3; do for b in 1 2 3; do [ "$a$b" = 22 ] && break 2; echo "$a$b"; done; done
Running this with Dash printed a=1 b=1, a=2 b=1 and a=3 b=1 for the first part, and 11, 12, 13 and 21 for the second. What does not carry over is the arithmetic test (( ... )) and the C-style for (( loop used in some examples above; use [ ] and a while loop for scripts that must run under sh (lessons 188 and 189).