Loops allow you to run one or more commands multiple times until a certain condition is met. However, sometimes you may need to alter the flow of the loop and terminate the loop or only the current iteration.
In Bash, break
and continue
statements allows you to control the loop execution.
break
StatementThe break
statement terminates the current loop and passes program control to the command that follows the terminated loop. It is used to exit from a for
, while
, [until](https://linuxize.com/post/bash-until-loop/)
, or select
loop. s The syntax of the break
statement takes the following form:
break [n]
Copy
[n]
is an optional argument and must be greater than or equal to 1. When [n]
is provided, the n-th enclosing loop is exited. break 1
is equivalent to break
.
To better understand how to use the break
statement, let’s take a look at the following examples.
In the script below, the execution of the [while](https://linuxize.com/post/bash-while-loop/)
loop will be interrupted once the current iterated item is equal to 2
:
i=0
while [[ $i -lt 5 ]]
do
echo "Number: $i"
((i++))
if [[ $i -eq 2 ]]; then
break
fi
done
echo 'All Done!'
Copy
Number: 0
Number: 1
All Done!
#bash #bash break #bash continue statement