In bash we have For and While Loop which used to iterate things again and again. But Sometime we need to continue or break loop in such a way that loop get iterate again with next value or just get exit. This can done through continue and break statement in For and While loop. let’s explain and see how it works.

Continue statement in For and While Loop

Sometime we like to continue our Loop with skip our current condition, Like we want to do some stuff in Loop in continually manner but whenever some conditions meet during Loop, we like to skip our work for that condition only. This kind of thing can be done by through continue statement.
Let’s see examples in both For and While Loop


                   Continue statement in For Loop
#!/bin/bash
for (( a=0; a<=5 ; a++ ))
do
if [ $a -eq 3 ]; then
continue
fi
echo $a
done
         OutPut
#./for_continue
0
1
2
4
5
========================================
         Continue statement in While Loop
#!/bin/bash
a=0
while [ $a -le 5 ]
do
if [ $a -eq 3 ];then
(( a++ ))
continue
fi
echo $a
(( a++ ))
done
         OutPut
#./for_continue
0
1
2
4
5

Break statement in For and While Loop

Sometime we like to exit from For or While Loop if some condition meet. This condition can be achieve with break statement in Loop. Let’s see how it works with some small code examples


                  Break statement with For Loop
#!/bin/bash
for (( a=0; a<=5 ; a++ ))
do
if [ $a -eq 3 ]; then
break
fi
echo $a
done
         OutPut
#./for_break
0
1
2
========================================
         Break statement with while Loop
#!/bin/bash
a=0
while [ $a -le 5 ]
do
if [ $a -eq 3 ];then
(( a++ ))
break
fi
echo $a
(( a++ ))
done
         OutPut
#./while_break
0
1
2