How to Use continue in Bash: Syntax and Examples
In bash, use the
continue statement inside loops to skip the remaining commands in the current iteration and move to the next iteration immediately. It works with for, while, and until loops to control flow efficiently.Syntax
The continue statement is used inside loops to skip the rest of the current iteration and start the next one. You can optionally specify a number to skip multiple nested loops.
continue: skips the current loop iteration.continue N: skips the rest of the current iteration of the Nth enclosing loop.
bash
continue continue N
Example
This example shows a for loop that prints numbers from 1 to 5 but skips printing the number 3 using continue.
bash
#!/bin/bash for i in {1..5}; do if [ "$i" -eq 3 ]; then continue fi echo "Number: $i" done
Output
Number: 1
Number: 2
Number: 4
Number: 5
Common Pitfalls
One common mistake is using continue outside of loops, which causes an error. Another is forgetting that continue only skips the current iteration, not the entire loop. Also, when using nested loops, continue without a number affects only the innermost loop.
bash
# Wrong: continue outside loop # continue # Correct usage inside loop for i in {1..3}; do if [ "$i" -eq 2 ]; then continue fi echo "$i" done
Output
1
3
Quick Reference
| Usage | Description |
|---|---|
| continue | Skip rest of current loop iteration and start next |
| continue N | Skip rest of current iteration of Nth enclosing loop |
| Used inside loops only | Causes error if used outside loops |
| Works with for, while, until | Controls loop flow efficiently |
Key Takeaways
Use
continue inside loops to skip the rest of the current iteration and proceed to the next.You can specify a number with
continue to skip iterations in outer loops when nested.Never use
continue outside of loops as it causes errors.Remember
continue affects only the current iteration, not the entire loop.Works with all loop types:
for, while, and until.