Last Updated : 15 Sep, 2023
The break
command in Linux is primarily used within loops to exit or terminate the loop prematurely based on certain conditions. It offers a quick and convenient way to escape from a loop's execution, whether it's a for
loop, a while
loop, or a nested loop structure. It can also take one parameter i.e.[N]. Here n is the number of nested loops to break. The default number is 1.
break [n]
When the break
command is encountered within a loop, the loop immediately terminates, and the program flow continues with the statement immediately following the loop.
#!/bin/bash
for i in {1..5}; do
echo $i
if [ $i -eq 3 ]; then
break
fi
done
echo "For loop terminated"
In this example, the break
statement is triggered when the value of i
becomes 3. As a result, the loop terminates.
If we want to print numbers from 1 to 10 using a while
loop, but halt the loop when the number 7 is reached.
#!/bin/bash
count=1
while [ $count -le 10 ]; do
echo $count
if [ $count -eq 7 ]; then
break
fi
((count++))
done
echo "While loop terminated"
In this case, the loop iterates through the numbers, but the break
statement comes into play when count
becomes 7. As a result, the loop terminates early.
In this example we will printing numbers from 1 to 5 using an until
loop but stopping when the number 4 is encountered.
#!/bin/bash
number=1
until [ $number -gt 5 ]; do
echo $number
if [ $number -eq 4 ]; then
break
fi
((number++))
done
echo "Until loop terminated"
In this case the loop continues until number
becomes greater than 5. However, the break
statement intervenes when number
reaches 4, leading to an early termination.
We can access this information using the break --help
command. Simply execute the following in our terminal.
break --helpConclusion
In this aarticle we have discussed about `break` command in Linux which exits loops based on conditions. It's versatile across loop types, including nested ones, and uses syntax like break [n]
. Whether ending for
, while
, or until
loops, break
streamlines scripting. Plus, break --help
offers easy access to help information.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4