hithesh
hithesh

Reputation: 439

Breaking out of a nested loop in 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.

Upvotes: 13

Views: 16176

Answers (1)

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

Upvotes: 30

Related Questions