Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of a nested loop in bash

Tags:

bash

How do you break out of a nested loop in bash?

Tried continue and break. break worked. But want to learn more.

for i in 1 2 3; do 
  if [[ $flag -eq 1 ]]; then
    break
  fi
done

How does break actually know the loop is nested? Instead of break, can I use i=4 or something out of range to exit from a loop.

like image 336
hithesh Avatar asked Jan 23 '26 02:01

hithesh


1 Answers

Use break followed by a number, to break out of that many levels of nesting. Example:

for i in 1 2 3 4 5; do
    echo
    echo i = $i
    for j in 1 2 3 4 5; do
        echo j = $j
        if [ $j -eq 4 ]; then break; fi
        if [ $j -eq 3 ] && [ $i -eq 4 ]; then break 2; fi
    done
done

Result:

i = 1
j = 1
j = 2
j = 3
j = 4

i = 2
j = 1
j = 2
j = 3
j = 4

i = 3
j = 1
j = 2
j = 3
j = 4

i = 4
j = 1
j = 2
j = 3
like image 174
Joseph Sible-Reinstate Monica Avatar answered Jan 24 '26 20:01

Joseph Sible-Reinstate Monica