Bash by Example: Loop Control (Continue)
Skipping the rest of the current iteration using the continue statement to immediately jump to the next loop cycle, implementing conditional processing within loops, filtering items during iteration, and avoiding deeply nested conditionals by using continue for guard clauses.
Code
#!/bin/bash
echo "Printing odd numbers only:"
for i in {1..10}; do
# Check if number is even
if (( i % 2 == 0 )); then
# Skip to next iteration
continue
fi
echo "Odd: $i"
done
echo "Done."Explanation
The continue statement skips the remainder of the current loop iteration and jumps back to the condition check (or the next item in the list). It effectively says "I'm done with this item, let's move to the next one."
This is useful for filtering items or avoiding deep nesting of if statements. Instead of wrapping the entire loop body in a huge if block, you can check for exclusion criteria at the top and continue if they are met.
Like break, continue accepts an optional integer argument (e.g., continue 2) to resume the Nth enclosing loop, though this is less commonly used.
Code Breakdown
((...)) to check if i is divisible by 2 (even).continue stops processing the current number. The echo command on line 12 is skipped for all even numbers.
