How to Use the Continue Command in Bash

Updated on 30 July, 2025
Learn the continue command in Bash to control loop iterations, skip conditions, and optimize script logic efficiently.
How to Use the Continue Command in Bash header image

The continue command in Bash allows you to skip the remaining commands in the current loop iteration and proceed directly to the next one. It is useful when you want to bypass specific conditions without exiting the loop entirely. Unlike the break command, which terminates the loop, continue enables precise control over iteration flow.

This article demonstrates how to use continue with for, while, until, select, and nested loops to optimize Bash scripts for tasks like filtering input, skipping invalid data, and managing conditional execution.

Use Bash continue with a for Loop

Use the continue command in for loops to skip over specific items without terminating the loop. This is useful when processing lists, ranges, or arrays where you want to exclude certain elements based on a condition.

Command Syntax

for variable in list; do
    [condition] && continue   # Skip to next iteration
    [condition] && break      # Exit loop
done

Command Demonstration

Basic List Loop

Skip a specific item in the list and stop after a match.

bash
#!/bin/bash
# Skip "banana" and exit when "cherry" is reached

for item in apple banana watermelon cherry pixie; do
    [[ "$item" == "banana" ]] && continue  
    [[ "$item" == "cherry" ]] && break    
    echo "Processing: $item"
done

Output:

Processing: apple
Processing: watermelon

Numeric Range Loop

Skip even numbers and stop when the value exceeds 17.

bash
#!/bin/bash
# Process odd numbers and exit after reaching a threshold

for i in {10..20}; do
    (( i % 2 == 0 )) && continue  
    (( i > 17 )) && break         
    echo "Odd number: $i"
done

Output:

Odd number: 11
Odd number: 13
Odd number: 15
Odd number: 17

Array Loop with Processing Limit

Skip multiples of 3 and stop after handling 4 valid numbers.

bash
#!/bin/bash
numbers=(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
processed_count=0

for num in "${numbers[@]}"; do
    (( num % 3 == 0 )) && continue  

    echo "Processing number: $num"
    ((processed_count++))

    if (( processed_count >= 4 )); then
        echo "Processing limit reached"
        break
    fi
done

Output:

Processing number: 1
Processing number: 2
Processing number: 4
Processing number: 5
Processing limit reached

C-Style for Loop

Skip a specific iteration and exit after a threshold.

bash
#!/bin/bash
for ((i = 1; i <= 10; i++)); do
    (( i == 5 )) && continue      # Skip 5
    (( i == 8 )) && break         # Exit at 8
    echo "Number: $i"
done

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 6
Number: 7

Use continue in for loops to efficiently bypass items based on conditions, whether processing strings, ranges, or arrays. These examples demonstrate list filtering, range skipping, and controlled loop exits.

Use Bash continue with a Nested Loop

In nested loop structures, you can use continue n to control which loop level resumes its next iteration. The default continue (or continue 1) affects the innermost loop. Using continue 2 skips the remaining steps in both the inner and outer loop bodies and resumes the next iteration of the second-level loop.

Command Syntax

for outer in list; do
    for inner in list; do
        [condition] && continue [n]  # Skip to next iteration of nth loop
        [condition] && break [n]     # Exit nth loop
    done
done

Command Demonstration

This example simulates a car inspection system. It skips certain combinations based on brand and model and applies quotas per brand.

bash
#!/bin/bash
# Car inspection process for different brands and models

brands=("Toyota" "Honda" "Ford")
models=("Sedan" "SUV" "Truck")

for brand in "${brands[@]}"; do
    echo "Inspecting $brand vehicles:"
    processed_models=0

    for model in "${models[@]}"; do
        # Skip Honda SUVs (under maintenance)
        if [[ "$brand" == "Honda" && "$model" == "SUV" ]]; then
            echo "  Skipping $brand $model (maintenance required)"
            continue
        fi

        # Exit Ford brand after inspecting the first model
        if [[ "$brand" == "Ford" && "$model" == "SUV" ]]; then
            echo "  End of shift - stopping Ford inspection"
            continue 2
        fi

        echo "  ✓ $brand $model - Ready for sale"
        ((processed_models++))

        # Stop after inspecting 2 models for a brand
        if (( processed_models >= 2 )); then
            echo "  Daily quota reached for $brand"
            break
        fi
    done
    echo ""
done

Output:

Inspecting Toyota vehicles:
  ✓ Toyota Sedan - Ready for sale
  ✓ Toyota SUV - Ready for sale
  Daily quota reached for Toyota

Inspecting Honda vehicles:
  ✓ Honda Sedan - Ready for sale
  Skipping Honda SUV (maintenance required)
  ✓ Honda Truck - Ready for sale
  Daily quota reached for Honda

Inspecting Ford vehicles:
  ✓ Ford Sedan - Ready for sale
  End of shift - stopping Ford inspection

Use continue n carefully in nested loops to avoid unintentionally skipping multiple loop levels. A misplaced continue 2 can prematurely exit critical logic in the outer loop.

Use Bash Continue with a while Loop

In while loops, the continue command allows you to skip the remaining statements in the current iteration and proceed directly to the next one. This is useful for filtering out unwanted conditions without exiting the loop entirely.

Command Syntax

while [condition]; do
    [condition] && continue   # Skip to next iteration
    [condition] && break      # Exit loop
done

Command Demonstration

The following example filters server log entries and only processes those that begin with ERROR. It skips blank lines and non-error entries.

bash
#!/bin/bash
# Analyze server log entries for errors

log_entries=(
    "INFO: User login successful"
    "ERROR: Database connection failed"
    ""
    "WARNING: High memory usage"
    "ERROR: File not found"
    "INFO: Backup completed"
    "DEBUG: Cache cleared"
)

error_count=0
index=0
total=${#log_entries[@]}

while (( index < total )); do
    entry="${log_entries[index]}"
    ((index++))

    # Skip empty log lines
    if [[ -z "$entry" ]]; then
        continue
    fi

    # Skip non-error entries
    if [[ "$entry" != ERROR* ]]; then
        continue
    fi

    # Process error entries
    echo "Found error: $entry"
    ((error_count++))

    # Stop after finding 2 errors
    if (( error_count >= 2 )); then
        echo "Maximum errors reached for analysis"
        break
    fi
done

Output:

Found error: ERROR: Database connection failed
Found error: ERROR: File not found
Maximum errors reached for analysis

The script uses continue to skip over blank or non-error log entries, reducing unnecessary processing and focusing only on actionable items.

Use Bash continue with an until Loop

In an until loop, continue skips the current iteration and returns to the loop condition check. This is useful for ignoring invalid input or conditions until a specific goal is met.

Command Syntax

until [condition]; do
    [condition] && continue   # Skip to next iteration
    [condition] && break      # Exit loop
done

Command Demonstration

The following example implements a number-guessing game that validates user input before processing.

bash
#!/bin/bash
# Number guessing game with input validation

# Generate a random number between 1 and 10
target=$((RANDOM % 10 + 1))
echo "Guess the number between 1 and 10:"

until false; do
    read -p "Enter your guess: " guess

    # Skip if input is empty
    if [[ -z "$guess" ]]; then
        echo "Please enter a number!"
        continue
    fi

    # Skip if not a number
    if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
        echo "That's not a valid number!"
        continue
    fi

    # Skip if out of range
    if (( guess < 1 || guess > 10 )); then
        echo "Number must be between 1 and 10!"
        continue
    fi

    # Check if guess is correct
    if (( guess == target )); then
        echo "Congratulations! You guessed it: $target"
        break
    else
        echo "Wrong! Try again."
        continue
    fi
done

Output:

Guess the number between 1 and 10:
Enter your guess: 1
Wrong! Try again.
Enter your guess: 2
Wrong! Try again.
Enter your guess: 3
Congratulations! You guessed it: 3

The script uses continue to filter out empty, non-numeric, and out-of-range inputs. Only valid guesses are evaluated against the target number.

Use Bash continue with a select Loop

A select loop displays a numbered menu based on a list of options. You can use the continue command to handle invalid or empty input by redisplaying the menu, ensuring that only valid selections trigger the intended actions.

Command Syntax

select variable in option1 option2 option3; do
    case $variable in
        option1) command1 ;;
        option2) command2 ;;
        *) continue ;;  # Invalid choice - redisplay menu
    esac
    break  # Exit after valid selection
done

Command Demonstration

The following example implements a car service booking menu that handles invalid selections using continue.

bash
#!/bin/bash
# Car service booking system

services=("Oil Change" "Tire Rotation" "Brake Check" "Car Wash" "Exit")

echo "=== Auto Service Menu ==="
echo "What service do you need today?"

select service in "${services[@]}"; do
    # Handle invalid selections (e.g., input out of range)
    if [[ -z "$service" ]]; then
        echo "Please enter a number between 1 and ${#services[@]}"
        continue
    fi

    # Exit option
    if [[ "$service" == "Exit" ]]; then
        echo "Thanks for visiting!"
        break
    fi

    # Process valid service
    echo "$service booked!"
    break
done

Output:

=== Auto Service Menu ===
What service do you need today?
1) Oil Change
2) Tire Rotation
3) Brake Check
4) Car Wash
5) Exit
#? 6
Please enter a number between 1 and 5
#? 7
Please enter a number between 1 and 5
#? 1
Oil Change booked!

The continue command is useful for redisplaying the menu when an invalid selection is made. Valid choices trigger an action and then exit the loop.

Conclusion

In this article, you used the continue command to control iteration flow in Bash scripts across for, while, until, select, and nested loops. You applied targeted iteration skipping to handle data validation, user input, and loop optimization without exiting the loop prematurely. These techniques help make your scripts more efficient and easier to manage.

Tags:

Comments

No comments yet.