LinuxCommandLibrary

continue

Skip current loop iteration and continue

TLDR

Skip to the next iteration

$ while :; do continue; [echo "This will never be reached"]; done
copy

Skip to the next iteration from within a nested loop
$ for i in [{1..3]}; do [echo $i]; while :; do continue 2; done; done
copy

SYNOPSIS

continue [n]

PARAMETERS

n
    Optional positive integer; specifies the nesting level of the enclosing loop to continue (default: 1, innermost loop)

DESCRIPTION

The continue command is a shell built-in used within looping constructs like for, while, until, and select to prematurely end the current iteration and proceed to the next one. It skips any remaining statements in the loop body for that cycle, effectively ignoring conditions or actions until the loop restarts.

This is particularly useful for filtering or conditional skipping without breaking the entire loop. For instance, in processing files or numbers, you might skip invalid entries while continuing with valid ones. Unlike break, which exits the loop entirely, continue preserves the loop's overall execution.

In nested loops, specifying a numeric argument allows targeting a specific enclosing loop level, enhancing control in complex scripts. It's efficient for performance-critical scripts, avoiding unnecessary computations. Available in major shells like Bash, Zsh, and Dash, it follows POSIX standards for portability across Unix-like systems.

Common use cases include data validation, error skipping in batch processing, or optimizing iterations over large datasets.

CAVEATS

continue must be inside a loop, or it causes a syntax error. Invalid n (zero/negative or exceeding nesting) leads to errors. Not usable in functions or scripts without loops.

EXAMPLE

for i in {1..5}; do
  if [ $i -eq 3 ]; then continue; fi
  echo "Processing $i"
done

Output:
Processing 1
Processing 2
Processing 4
Processing 5

NESTED LOOP EXAMPLE

for outer in 1 2; do
  for inner in a b; do
    if [ $inner = 'b' ]; then continue 2; fi
    echo "$outer $inner"
  done
done

Skips 'b' in inner, targeting outer loop.

HISTORY

Originated in early Unix shells like Bourne shell (1977). Standardized in POSIX.2 (1992) and later POSIX.1-2008. Evolved with shell enhancements for nested loop support.

SEE ALSO

break(1), bash(1), zsh(1), dash(1)

Copied to clipboard