SinaMathew
SinaMathew

Reputation: 15

Break out of inner loop in a nested loop (BASH)

I decide to play around loop just to understand how loops work in bash. But I am the one who got played. All I know is the the break call helps to stop a particular loop

echo "For loop begins"
for (( a = 1; a < 10; a++ ))
do
        echo -e "\tOuter loop ${a}"
        for (( b = 1; b < 100; b++ ))
        do
                if [[ ${b} -gt 5 ]]
                then
                        break 2
                fi
                echo -e "\t\tInner loop ${b}"
        done
done
echo "For loop completed"

So fortunate that the break 2 call also breaks out of the outer loop.

I already tried cahanging my for loop to for (( a = 1; a <= 10; a++ )) and the second one to for (( b = 1; b <= 100; b++ )) putting <= instead of < but I still get same output.

genius@GeniusDPhil-hp250g1notebookpc:~$ ./loop.sh 
For loop begins
        Outer loop 1
                Inner loop 1
                Inner loop 2
                Inner loop 3
                Inner loop 4
                Inner loop 5
For loop completed
genius@GeniusDPhil-hp250g1notebookpc:~$ 

I was expecting the outer loop to run 10 times, does break also take me out of my outer loop? if yes how do I use break properly? if no the what's the issue?

NOTE: The programmer in me is 3 months old.

Upvotes: 1

Views: 790

Answers (1)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185161

What I would do:

echo "For loop begins"
for (( a = 1; a <= 10; a++ ))
do
        echo -e "\tOuter loop ${a}"
        for (( b = 1; b < 100; b++ ))
        do
                if [[ ${b} -gt 5 ]]
                then
                        break
                fi
                echo -e "\t\tInner loop ${b}"
        done
done
echo "For loop completed"

Note the use of break only, because break 2 break the outer loop too. The logic is wrong from your code if you need to iterate 10 times like I does here.

Check

man bash | less +/'^ +break'

break [n]
Exit from within a for, while, until, or select loop. If n is specified, break n levels. n must be ≥ 1. If n iq greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless n is not greater than or equal to 1.


Using modern , better use if (( b > 5 ))


((...)) and $((...)) are arithmetic commands, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.

See http://mywiki.wooledge.org/ArithmeticExpression

Upvotes: 0

Related Questions