continue - macOS


Overview

The continue command in macOS is used within looping constructs in shell scripts. It allows for the skipping of the remainder of the current iteration and forces the next iteration of the loop to begin. It is typically used to skip certain conditions within a loop without breaking out of the loop entirely.

Syntax

continue [n]
  • n: An optional argument specifying the number of enclosing loops to continue from. If n is provided, continue will skip out of the multiple nested loops according to the number specified.

Options/Flags

The continue command itself does not have additional options or flags. The optional numeric argument n controls how many levels of enclosing loops are affected:

  • continue: Continues with the next iteration of the innermost loop.
  • continue n: Continues with the next iteration of the nth enclosing loop.

Examples

  1. Skipping Specific Items in a Loop:

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

    Output excludes “Processing item 3”.

  2. Nested Loop Example:

    for i in {1..3}; do
        for j in {A..C}; do
            if [ $i -eq 2 -a $j == "B" ]; then
                continue 2
            fi
            echo "Processing $i $j"
        done
    done
    

    This will skip the rest of the loops for i=2 when j=B and continue with i=3.

Common Issues

  • Incorrect Loop Level:
    Using continue with a number higher than the nesting level of loops will result in an error. Always check the depth of loop nesting when using continue n.

  • Syntax Error:
    Forgetting the dollar sign $ before variable names in conditions (e.g., [ i -eq 3 ] should be [ $i -eq 3 ]) will lead to unexpected behavior or syntax errors.

Integration

The continue command is powerful when combined with other shell scripting components like if statements, for or while loops:

for file in *.txt; do
    grep -q 'Skip' "$file"
    if [ $? -eq 0 ]; then
        continue
    fi
    echo "Processing $file"
done

This script checks each text file for the presence of the word ‘Skip’; if found, the loop continues to the next file, skipping the echo statement.

  • break: Exits out of a loop entirely.
  • for, while, until: Loop constructs within which continue can be used.

View more about scripting in macOS in the Official Bash Reference Manual.