Break and Continue in Bash For Loop

Written by
Date: 2010-11-20 10:36:30 00:00

There are cases in which you may want to break the execution of a bash for loop, like if something happens that will prevent further execution, or of the goal of the task has been reached.

You use break to do stop the execution of the for loop.

Using break in a bash for loop

Here is how it works break

for i in [series]
do
        command 1
        command 2
        command 3
        if (condition) # Condition to break the loop
        then
                command 4 # Command if the loop needs to be broken
                break
    fi
        command 5 # Command to run if the "condition" is never true 
done

Using continue in a bash for loop

There are also times when you want to break the execution of the series of commands, for a certain value on the series, but do not stop the complete program. In that case you may use continue to stop the execution of commands over the present value but continue with the next value in the series.

Here is how:

for i in [series]
do
        command 1
        command 2
        if (condition) # Condition to jump over command 3
                continue # skip to the next value in "series"
        fi
        command 3
done

In this case, if the condition is true, the command 3 is not executed over that value, and the program jumps to the next one.

If you want to know more, check this bash for loop article