Gábor Varga
Gábor Varga

Reputation: 840

Loop first run continue in shell script

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++;
}

Upvotes: 1

Views: 8773

Answers (2)

l0b0
l0b0

Reputation: 58808

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

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

Reputation: 51613

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

Is one of the ways you can do it.

HTH

Upvotes: 0

Related Questions