Sunday, 3 March 2019

Break and Continue statement in shell script


All statement inside the loop executed as long as some condition are true.

If break placed inside the loop, when loop reach the break statement it will terminated out from the loop.
If continue placed inside the loop, when loop reach the continue statement it will not execute next lines of the loop and it will go to the next iteration.

script for break:
#!/bin/bash
x=0
while [ $x -le 5 ]
do
    echo "Before break : $x"
    x=`expr $x + 1`
    break
    echo "After breakn : $x"
done
echo "While loop finished"
output:
Before break : 0
While loop finished
script for continue:
#!/bin/bash
x=0
while [ $x -le 5 ]
do
    echo "Before continue : $x"
    x=`expr $x + 1`
    continue
    echo "After continue : $x"
done
echo "While loop finished"
    
output
Before continue : 0
Before continue : 1
Before continue : 2
Before continue : 3
Before continue : 4
Before continue : 5
While loop finished
script without break and continue:
#!/bin/bash
x=0
while [ $x -le 5 ]
do
    echo "Before operation : $x"
    x=`expr $x + 1`

    echo "After operation : $x"
done
echo "While loop finished"
   
output:
Before operation : 0
After operation : 1
Before operation : 1
After operation : 2
Before operation : 2
After operation : 3
Before operation : 3
After operation : 4
Before operation : 4
After operation : 5
Before operation : 5
After operation : 6
While loop finished



No comments:

Post a Comment