HowTo: Skip Bash For Loop

In Bash, you can skip a for loop iteration using the continue keyword. Here’s an example:

#!/bin/bash

for i in {1..10}
do
if [[ $i -eq 5 ]]; then
continue
fi

echo "Iteration $i"
done

In this example, we have a for loop that iterates from 1 to 10. Inside the loop, we have an if statement that checks if the current iteration is equal to 5. If it is, the continue keyword is used to skip the current iteration and move on to the next one. If the current iteration is not 5, the echo command is used to print a message to the console.

When you run this script, you’ll see that the message for iteration 5 is skipped:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 6
Iteration 7
Iteration 8
Iteration 9
Iteration 10

So, in summary, you can skip a for loop iteration in Bash using the continue keyword inside an if statement.

Leave a Comment