Open In App

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.

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

for i in {1..5}; do
echo $i
if [ $i -eq 3 ]; then
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.

while [ $count -le 10 ]; do
echo $count
if [ $count -eq 7 ]; then
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.

until [ $number -gt 5 ]; do
echo $number
if [ $number -eq 4 ]; then
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


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.

Article Tags :