Search code examples
bashfor-loopinfinite-loop

bash infinite loop over 3 values


I have 3 static values: aa, bb, cc. I want to loop over them indefinitely with exit case. Writing the simple loop is easy:

for i in aa bb cc; do 
   echo $i
done

But I want to loop over them indefinitely until some condition is meat:

for i in aa bb cc; do 
   echo $i
   if [ somecondition ]; then
      doSomething
      break
   fi
done

The somecondition depends on external conditions and on i. It should look like try to do something with i until success.

What is the best way to do that?


Solution

  • A simple way is to nest your code inside an infinite loop:

    while true; do
        for i in aa bb cc; do
            echo $i;
            if [ somecondition ]; then
                doSomething
                break 2
            fi
        done
    done
    

    Notice that the break command now has an argument 2.

    man bash says:

        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 is 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.