What is the purpose of the 'break' statement in bash?

The break statement in Bash is used to exit from a loop prematurely. It can be used within for, while, or until loops to terminate the loop's execution when a certain condition is met.

Purpose of the break Statement:

  1. Exiting Loops: It allows you to stop the execution of a loop based on a specific condition, rather than waiting for the loop to complete all its iterations.

  2. Control Flow: It provides a way to control the flow of the script, enabling you to skip the remaining iterations of the loop and continue executing the code that follows the loop.

Example Usage

Here’s a simple example demonstrating the use of break in a for loop:

#!/bin/bash

for i in {1..10}; do
    if [ $i -eq 5 ]; then
        echo "Breaking the loop at $i"
        break
    fi
    echo "Current number: $i"
done

echo "Loop has been exited."

Output

When you run the script, the output will be:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Breaking the loop at 5
Loop has been exited.

In this example, the loop iterates from 1 to 10, but when i equals 5, the break statement is executed, causing the loop to terminate early. The script then continues with the code that follows the loop.

0 Comments

no data
Be the first to share your comment!