HowTo: Skip Bash For Loop

HowTo: Skip Bash For Loop

To skip a for loop in Bash, you can use the continue keyword. This will cause the for loop to immediately move on to the next iteration, skipping any remaining code in the current iteration.

Here is an example of how to use the continue keyword to skip a for loop iteration:

r‮efe‬r to:lautturi.com
for i in {1..10}; do
  if [ $i -eq 5 ]; then
    continue
  fi
  echo $i
done

In this example, the for loop will iterate through the numbers 1 to 10. Inside the loop, an if statement is used to check if the current value of $i is equal to 5. If it is, the continue keyword is used to immediately move on to the next iteration of the loop. If the value of $i is not equal to 5, the echo command is used to print the value to the console.

This will output the numbers 1 to 10, but it will skip the number 5, because the continue keyword causes the for loop to immediately move on to the next iteration when $i is equal to 5. The output will look like this:

1
2
3
4
6
7
8
9
10

Note that the continue keyword only affects the current iteration of the for loop. It does not cause the loop to stop running altogether. If you want to stop the loop completely, you can use the break keyword instead. Consult the Bash documentation for more information about using continue and break in for loops.

Created Time:2017-10-16 14:38:51  Author:lautturi