Syntax of `break` command in Linux
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.
Example 1: Using break statement in for 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.
Example 2: Using break statement in while loop
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.
Example 3: Using break statement in until loop
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.
break –help : It displays help information.
We can access this information using the break --help
command. Simply execute the following in our terminal.
break --help
break command in Linux with examples
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.