break – End a for, while or until loop

break is a Linux command used to exit a loop statement immediately. It is often used in conjunction with for, while, and until loops to terminate the loop prematurely based on a certain condition.

Overview

The break command is used to exit a loop statement immediately. It is often used in conjunction with for, while, and until loops to terminate the loop prematurely based on a certain condition.

Here is the basic syntax of the break command:

break [n]

Where n is an optional argument that specifies the number of nested loops to break out of. If n is not provided, the break command will exit the innermost loop.

Here is an example of how to use the break command in a for loop:

for i in {1..10}
do
    if [ $i -eq 5 ]
    then
        break
    fi
    echo $i
done

In this example, the for loop will iterate from 1 to 10, but when i is equal to 5, the break command will be executed, and the loop will terminate prematurely.

Here is an example of how to use the break command in a while loop:

while true
do
    read -p "Enter a number: " num
    if [ $num -eq 0 ]
    then
        break
    fi
    echo "You entered $num"
done

In this example, the while loop will continue to prompt the user for input until they enter a value of 0. When the user enters 0, the break command will be executed, and the loop will terminate.

Here is an example of how to use the break command in an until loop:

until [ $num -eq 0 ]
do
    read -p "Enter a number: " num
    echo "You entered $num"
done

In this example, the until loop will continue to prompt the user for input until they enter a value of 0. When the user enters 0, the break command is not needed as the loop will terminate automatically.

Options

The break command does not have any options.

Troubleshooting tips

  • Make sure the break command is used within a loop statement.
  • Double-check that the condition for the loop termination is correct.
  • Ensure that the break command is not used outside of a loop statement, as it will result in an error.

Notes

  • The break command can only be used within a loop statement.
  • If the break command is used within nested loops, the n argument can be used to specify the number of loops to break out of.