Bash Continue Statement

In Bash, the continue statement is used to skip the rest of the current iteration in a loop and move on to the next iteration. It allows you to bypass certain parts of the loop’s code block and proceed with the next iteration. Here’s an example that demonstrates the usage of the continue statement in a for loop:

#!/bin/bash

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

In this example, the for loop iterates over the numbers from 1 to 5. Inside the loop, there is an if statement that checks if the value of number is equal to 3. If the condition is true, the continue statement is executed, and the remaining code for that iteration is skipped. This means that when the loop encounters the number 3, it will skip the echo statement and move on to the next iteration.

When you run this script, it will output:

Number: 1
Number: 2
Number: 4
Number: 5

The loop iterates through the numbers 1 to 5, but when it reaches 3, the continue statement is encountered, and the echo statement for that iteration is skipped. As a result, the number 3 is not printed.

The continue statement can be used in while and until loops as well. It provides a way to control the flow of your loop by skipping certain parts of the loop’s code block based on specific conditions.

Note that similar to the break statement, if you have nested loops, the continue statement will only skip the current iteration in the innermost loop. The control will then move to the next iteration of the innermost loop.

Overall, the continue statement allows you to selectively skip parts of a loop’s code block and proceed to the next iteration, providing flexibility in loop control flow.

Leave a Comment

Your email address will not be published. Required fields are marked *