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
    An optional integer specifying the N-th enclosing for, while, until, or select loop to continue. If 'n' is omitted, it defaults to 1, meaning the innermost loop. 'n' must be an integer greater than or equal to 1.

DESCRIPTION

The continue command is a shell built-in that alters the flow of control within looping constructs such as for, while, until, and select loops.

When encountered inside a loop, continue causes the rest of the commands in the current iteration of that loop to be skipped immediately. Execution then jumps directly to the beginning of the next iteration, re-evaluating the loop's condition or fetching the next item, depending on the loop type.

It is commonly used with conditional statements (e.g., if) to bypass specific steps for certain data or conditions within a loop, without terminating the entire loop. This differentiates it from the break command, which exits the loop entirely.

CAVEATS

continue is a shell built-in command, not an external executable program found in your system's PATH. It is directly interpreted by the shell (e.g., Bash, Zsh).

It must be used within the body of a looping construct. Using it outside a loop will result in a syntax error or a non-zero exit status.

If 'n' is specified and exceeds the number of enclosing loops, an error occurs, and the command exits with a non-zero status.

USAGE EXAMPLE

A simple example demonstrating how continue skips processing for a specific item within a loop:

#!/bin/bash
for i in 1 2 3 4 5
do
if [ $i -eq 3 ]; then
echo "Skipping number $i..."
continue
fi
echo "Processing number $i"
done
echo "Loop finished."


Output of the above script:
Processing number 1
Processing number 2
Skipping number 3...
Processing number 4
Processing number 5
Loop finished.

HISTORY

The concept of a continue statement for altering loop flow control is fundamental in many programming languages (e.g., C, Java, Python). Its inclusion in Unix shells like sh and later Bash is a natural extension of these control structures to scripting. It has been a standard part of POSIX shell specifications and is widely available across different Unix-like systems, providing a consistent way to manage loop iterations in shell scripts since early versions of the shell.

SEE ALSO

break(1), bash(1), sh(1)

Copied to clipboard