5
while [condition]
do
  for [condition]
  do
    if [ "$x" > 3 ];then
      break
    fi
  done

  if [ "$x" > 3 ];then
    continue
  fi
done

In the above script I have to test "$x" > 3 twice. Actually the first time I test it, if it is true I want to escape the while loop and continue to the next while loop.

Is there any simpler way so I can use something like continue 2 to escape the outer loop?

2
  • 2
    Why not use continue 2 in the inner loop? Commented Oct 25, 2012 at 23:18
  • 1
    yes continue n . Also are you sure about ` for [ condition ] ... usually it for n in a b c` or similar. Good luck. Commented Oct 26, 2012 at 0:35

2 Answers 2

1

"break" and "continue" are close relatives of "goto" and should generally be avoided as they introduce some nameless condition that causes a leap in the control flow of your program. If a condition exists that makes it necessary to jump to some other part of your program, the next person to read it will thank you for giving that condition a name so they don't have to figure it out!

In your case, your script can be written more succinctly as:

dataInRange=1
while [condition -a $dataInRange]
do
  for [condition -a $dataInRange]
  do
    if [ "$x" > 3 ];then
      dataInRange=0
    fi
  done
done
Sign up to request clarification or add additional context in comments.

Comments

0

This bash script helps me better understand how to continue on outer loops from nested loop.

Basically you need to use continue [n] where n is the number of loops counting FROM the loop you're going to write continue TO external loops

#!/bin/bash

for A in {1..2}; do
  echo "Loop A: A$A"
  for B in {1..2}; do
    echo "  Loop B: B$B"
    for C in {1..2}; do
      echo "    Loop C: C$C"
      
      if [[ $C -eq 2 ]]; then
        echo "    Skipping iteration of Loop A from inside Loop C"
        continue 3  # SKIP current iteration on Loop A
      fi
      
      for D in {1..2}; do
        echo "      Loop D: D$D"
        
        if [[ $D -eq 1 ]]; then
          echo "      Skipping iteration of Loop C from inside Loop D"
          continue 2  # SKIP current iteration on Loop C
        fi
        
      done
    done
  done
done

it prints:

Loop A: A1
  Loop B: B1
    Loop C: C1
      Loop D: D1
      Skipping iteration of Loop C from inside Loop D
    Loop C: C2
    Skipping iteration of Loop A from inside Loop C
Loop A: A2
  Loop B: B1
    Loop C: C1
      Loop D: D1
      Skipping iteration of Loop C from inside Loop D
    Loop C: C2
    Skipping iteration of Loop A from inside Loop C

Comments

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.