Break And Continue Statement In Shell Script

The very basic difference between exit, break and continue statement is that exit instruct the interpreter to exit from the entire shell script however break statement instruct interpreter to exit from the loop condition and execute rest line of code within the shell script and in the same way continue instruct interpreter to exit only the met condition and execute rest of the condition in the loop which is not satisfying the condition.

Break & Continue statement always used inside the loops condition.

#!/bin/bash

#set -xv

echo "1st Loop Condition is going to execute now"

for i in $(seq 10)

do

        if [[ ${i} -eq 5 ]];

then

                break;

        fi

echo "${i}"

done

echo "We're outside Of the 1st loop"

echo "2nd Loop Condition is going to execute now"

for j in $(seq 10)

do

        if  [[ ${j} -eq 6 ]] || [[ ${j} -eq 8 ]] || [[ ${j} -eq 10 ]]

then

        continue

fi

echo ${j}

done

echo "We're Outside Of The 2nd Loop"

##### CODE ENDS HERE

 [root@LAPTOP-U2OPV1ET loops]# ./break_continue.sh

1st Loop Condition is going to execute now

1

2

3

4

We're outside Of the 1st loop

2nd Loop Condition is going to execute now

1

2

3

4

5

7

9

We're Outside Of The 2nd Loop

Post a Comment

Previous Post Next Post