continue – End this loop and continue to execute the next for, while or until loop

The continue command is used in Linux to end the current iteration of a loop and continue with the next iteration of the same loop or to execute the next loop (for, while, or until).

Overview

The continue command is used to skip the current iteration of a loop and continue with the next iteration of the same loop or to execute the next loop (for, while, or until). This command is useful when you want to skip a specific iteration of a loop without terminating the entire loop.

The syntax of the continue command is as follows:

continue [n]

Here, n is an optional argument that specifies the number of loops to skip. If n is not specified, the continue command will skip the current iteration of the loop.

Examples

Example 1:

#!/bin/bash
for i in {1..5}
do
    if [ $i -eq 3 ]
    then
        continue
    fi
    echo "Iteration number: $i"
done

Output:

Iteration number: 1
Iteration number: 2
Iteration number: 4
Iteration number: 5

In this example, the continue command is used to skip the third iteration of the loop and continue with the next iteration.

Example 2:

#!/bin/bash
i=1
while [ $i -le 5 ]
do
    if [ $i -eq 3 ]
    then
        i=$((i+1))
        continue
    fi
    echo "Iteration number: $i"
    i=$((i+1))
done

Output:

Iteration number: 1
Iteration number: 2
Iteration number: 4
Iteration number: 5

In this example, the continue command is used to skip the third iteration of the loop and continue with the next iteration.

Options

The continue command does not have any options.

Troubleshooting Tips

  • Make sure that the continue command is used within a loop.
  • The continue command will only skip the current iteration of the loop. If you want to skip multiple iterations, you can use a counter variable and increment it accordingly.
  • If you are using the continue command within a nested loop, it will skip the current iteration of the innermost loop.

Notes

  • The continue command is useful when you want to skip a specific iteration of a loop without terminating the entire loop.
  • The continue command can be used with for, while, and until loops.