Skip to content

Latest commit

 

History

History
80 lines (60 loc) · 2.12 KB

02.Loop_control statements_(break, continue).md

File metadata and controls

80 lines (60 loc) · 2.12 KB

Loop Control Statements in Linux

1. Break Statement

The break statement in Bash is used to exit a loop prematurely based on a certain condition. It is typically used to terminate a loop when a specific condition is met. Here is the basic syntax:

while [ condition ]
do
    # Commands to be executed
    if [ some_condition ]
    then
        break
    fi
done
  • condition: Represents the loop's main condition.
  • some_condition: A condition that, when true, triggers the break statement, causing the loop to terminate.

Example:

counter=1
while [ $counter -le 10 ]
do
    echo "Iteration $counter"
    if [ $counter -eq 5 ]
    then
        break
    fi
    ((counter++))
done

This loop will print the numbers from 1 to 5 and then exit due to the break statement.

2. Continue Statement

The continue statement in Bash is used to skip the rest of the commands within a loop for the current iteration and move on to the next iteration. It is useful when you want to bypass specific iterations based on a condition. The syntax is as follows:

while [ condition ]
do
    # Commands to be executed
    if [ some_condition ]
    then
        continue
    fi
    # More commands that will be skipped if the continue statement is triggered
done
  • condition: Represents the loop's main condition.
  • some_condition: A condition that, when true, triggers the continue statement, skipping the remaining commands for the current iteration.

Example:

for i in {1..5}
do
    if [ $i -eq 3 ]
    then
        continue
    fi
    echo "Iteration $i"
done

This loop will print all iterations except for 3, as the continue statement skips the echo command for that particular iteration.

Conclusion

Understanding the break and continue statements in Bash allows for more precise control over loop execution. These statements enhance the flexibility of loops by providing mechanisms to exit early or skip specific iterations based on certain conditions.


Next | Functions