15

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.

2
  • 11
    An if statement is not a loop, so there is no nested loop in your example. Commented Sep 15, 2019 at 23:34
  • 1
    Like most other languages, bash tracks the lexical scope of all statements. While interpreting the if statement, bash has made a note of the fact that it's part of a loop. That's how the break statement knows what to do. Commented Sep 16, 2019 at 0:43

1 Answer 1

34

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
Sign up to request clarification or add additional context in comments.

3 Comments

In your example, there are 2 for loops. Do the if loops count for break? The default number for break is 1?
@hithesh After someone responds to one of your comments, please don't make changes to it that would change the meaning of the response. Anyway, no, ifs aren't loops, so they don't count, and yes, the default is 1.
Since the anwer edit queue is full, let's use the comment section. break --help should also state relative information. It also worth to mention that a break will end all specified loop depth immediately. In other words, specified loops won't pass until their block end but stop their execution practically instantly. The behavior of "break" depends on the Bash version (e.g. "break" will cause the subshell to exit if reached it in its parent shell), and more information should be available in "Compatibility" details document: tiswww.case.edu/php/chet/bash/COMPAT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.