1

How to break out of infinite while loop in a shell script?

I want to implement the following PHP code in shell script(s):

$i=1; 
while( 1 ) {
  if ( $i == 1 ) continue;
  if ( $i > 9 ) break;
  $i++;
}
2
  • 1
    Since your code checks if $i == 1, and continues to the next iteration if the result is true, before incrementing $i, you actually hava an endless loop. Commented Nov 30, 2011 at 9:47
  • You have an endless loop in your php code. Commented Nov 30, 2011 at 9:49

2 Answers 2

1

break works in shell scripts as well, but it's better to check the condition in the while clause than inside the loop, as Zsolt suggested. Assuming you've got some more complicated logic in the loop before checking the condition (that is, what you really want is a do..while loop) you can do the following:

i=1
while true
do
    if [ "$i" -eq 1 ]
    then
        continue
    fi
    # Other stuff which might even modify $i
    if [ $i -gt 9 ]
    then
        let i+=1
        break
    fi
done

If you really just want to repeat something $count times, there's a much easier way:

for index in $(seq 1 $count)
do
    # Stuff
done
Sign up to request clarification or add additional context in comments.

Comments

0
i=1
while [ $i -gt 9 ] ; do
     # do something here 
     i=$(($i+1))
done

Is one of the ways you can do it.

HTH

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.