In Bash, the break
statement is used to exit or terminate a loop prematurely. It is commonly used when you want to stop the execution of a loop based on a certain condition. Here’s an example that demonstrates the usage of the break
statement in a for
loop:
#!/bin/bash
for number in {1..10}; do
if [ $number -eq 6 ]; then
break
fi
echo "Number: $number"
done
In this example, the for
loop iterates over the numbers from 1 to 10. Inside the loop, there is an if
statement that checks if the value of number
is equal to 6. If the condition is true, the break
statement is executed, and the loop is terminated. This means that the loop will stop iterating once it reaches the number 6.
When you run this script, it will output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
The loop iterates through the numbers 1 to 5, but when it reaches 6, the break
statement is encountered, and the loop terminates.
The break
statement can be used in while
and until
loops as well. It provides a way to control the flow of your loop based on certain conditions. When the break
statement is executed, the control transfers to the first line of code immediately following the loop.
Note that if you have nested loops, the break
statement will only exit the innermost loop. If you want to break out of multiple nested loops, you can use labels and the break
statement with the label to specify which loop to exit.
Overall, the break
statement gives you the flexibility to terminate a loop prematurely based on a specific condition, allowing you to control the flow of your script.