Advanced Bash-Scripting Guide: A complete guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 10. Loops and Branches | Next |
Commands Affecting Loop Behavior
The break and continue loop control commands [1] correspond exactly to their counterparts in other programming languages. The break command terminates the loop (breaks out of it), while continue causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle.
Example 10-19. Effects of break and continue in a loop
#!/bin/bash LIMIT=19 # Upper limit echo echo "Printing Numbers 1 through 20 (but not 3 and 11)." a=0 while [ $a -le "$LIMIT" ] do a=$(($a+1)) if [ "$a" -eq 3 ] || [ "$a" -eq 11 ] # Excludes 3 and 11 then continue # Skip rest of this particular loop iteration. fi echo -n "$a " done # Exercise for the reader: # Why does loop print up to 20? echo; echo echo Printing Numbers 1 through 20, but something happens after 2. ################################################################## # Same loop, but substituting 'break' for 'continue'. a=0 while [ "$a" -le "$LIMIT" ] do a=$(($a+1)) if [ "$a" -gt 2 ] then break # Skip entire rest of loop. fi echo -n "$a " done echo; echo; echo exit 0 |
The break command may optionally take a parameter. A plain break terminates only the innermost loop in which it is embedded, but a break N breaks out of N levels of loop.
Example 10-20. Breaking out of multiple loop levels
#!/bin/bash # break-levels.sh: Breaking out of loops. # "break N" breaks out of N level loops. for outerloop in 1 2 3 4 5 do echo -n "Group $outerloop: " for innerloop in 1 2 3 4 5 do echo -n "$innerloop " if [ "$innerloop" -eq 3 ] then break # Try break 2 to see what happens. # ("Breaks" out of both inner and outer loops.) fi done echo done echo exit 0 |
The continue command, similar to break, optionally takes a parameter. A plain continue cuts short the current iteration within its loop and begins the next. A continue N terminates all remaining iterations at its loop level and continues with the next iteration at the loop N levels above.
Example 10-21. Continuing at a higher loop level
#!/bin/bash # The "continue N" command, continuing at the Nth level loop. for outer in I II III IV V # outer loop do echo; echo -n "Group $outer: " for inner in 1 2 3 4 5 6 7 8 9 10 # inner loop do if [ "$inner" -eq 7 ] then continue 2 # Continue at loop on 2nd level, that is "outer loop". # Replace above line with a simple "continue" # to see normal loop behavior. fi echo -n "$inner " # 8 9 10 will never echo. done done echo; echo # Exercise for the reader: # Come up with a meaningful use for "continue N" in a script. exit 0 |
The continue N construct is difficult to understand and tricky to use in any meaningful context. It is probably best avoided. |
[1] | These are shell builtins, whereas other loop commands, such as while and case, are keywords. |