continue
Skip current loop iteration and continue
TLDR
Skip to the next iteration
Skip to the next iteration from within a nested loop
SYNOPSIS
continue [n]
PARAMETERS
n
Optional. Specifies the level of nested loops to continue. If omitted, continue applies to the innermost loop. A positive integer value will act on the nth enclosing loop.
DESCRIPTION
The continue command in Linux is used within looping constructs (such as for, while, and until loops) to skip the remainder of the current iteration and proceed directly to the next iteration. It essentially bypasses any code following the continue statement within the current iteration of the loop, preventing it from being executed. This is useful when you want to avoid processing certain loop iterations based on a specific condition. The loop will continue to iterate until its normal termination condition is met. The continue command's primary function is to provide more control over the execution flow within loops, allowing for selective skipping of certain iterations without completely exiting the loop. The user must use it within a loop statement or else the statement will result in an error.
CAVEATS
Using continue excessively can sometimes make code harder to read. Consider whether a different loop structure or conditional logic would improve clarity.
Using continue outside a loop construct is a syntax error and will cause the shell script to exit.
Only positive numbers are valid for 'n'.
EXAMPLES
Example 1: Skipping even numbers in a loop:
for i in 1 2 3 4 5; do if [ $((i % 2)) -eq 0 ]; then continue fi echo "Processing: $i" doneOutput: Processing: 1
Processing: 3
Processing: 5
Example 2: Using continue within nested loops to skip to the next iteration of the outer loop if a condition is met in the inner loop:
for i in 1 2 3; do for j in a b; do if [ "$i" -eq 2 ] && [ "$j" = "b" ]; then continue 2 # Continue the outer loop fi echo "i=$i, j=$j" done doneOutput:
i=1, j=a
i=1, j=b
i=2, j=a
i=3, j=a
i=3, j=b
HISTORY
The continue command is a standard feature in many programming languages and shell scripting environments, including the Bourne shell (sh) and its descendants like Bash. It has been part of shell scripting for a long time, providing a way to control loop execution flow.
Continue has remained largely unchanged in its functionality and usage over time.