The break
statement in Bash is used to exit a loop prematurely based on a certain condition. It is typically used to terminate a loop when a specific condition is met. Here is the basic syntax:
while [ condition ]
do
# Commands to be executed
if [ some_condition ]
then
break
fi
done
condition
: Represents the loop's main condition.some_condition
: A condition that, when true, triggers thebreak
statement, causing the loop to terminate.
Example:
counter=1
while [ $counter -le 10 ]
do
echo "Iteration $counter"
if [ $counter -eq 5 ]
then
break
fi
((counter++))
done
This loop will print the numbers from 1 to 5 and then exit due to the break
statement.
The continue
statement in Bash is used to skip the rest of the commands within a loop for the current iteration and move on to the next iteration. It is useful when you want to bypass specific iterations based on a condition. The syntax is as follows:
while [ condition ]
do
# Commands to be executed
if [ some_condition ]
then
continue
fi
# More commands that will be skipped if the continue statement is triggered
done
condition
: Represents the loop's main condition.some_condition
: A condition that, when true, triggers thecontinue
statement, skipping the remaining commands for the current iteration.
Example:
for i in {1..5}
do
if [ $i -eq 3 ]
then
continue
fi
echo "Iteration $i"
done
This loop will print all iterations except for 3, as the continue
statement skips the echo
command for that particular iteration.
Understanding the break
and continue
statements in Bash allows for more precise control over loop execution. These statements enhance the flexibility of loops by providing mechanisms to exit early or skip specific iterations based on certain conditions.