1

I am trying to learn unix and practicing loops. Can someone explain why the output is suspended after encountering continue statement?

Output suspends after Count : 4 and I have exit with Ctrl+C.

Code:

COUNT=0

while [ $COUNT -lt 10 ]
do
  if [ $COUNT = 5 ]
  then
     continue
  fi
  echo "Count : $COUNT"
  ((COUNT++))
done

echo "while loop finished"
exit 0
0

1 Answer 1

9

The reason is rather simple: Your continue statement instructs the shell to immediately skip execution to the next loop iteration.

Unfortunately you thereby skip the ((COUNT++)) part, meaning that once COUNT reaches 5, it will never be incremented again, and the while condition never be met, so you are stuck in an endless loop from that point onward.

If, as @steeldriver assumes, you instead wanted to break out of the loop at a COUNT of 5, the break statement would be the correct choice.

As a general remark, if you are interested in learning more on shell scripts, I would recommend GreyCat&Lhunath's Bash Guide. Also, running your scripts through shellcheck (also available as standalone program on many OS repositories) can help identify syntax errors and the like.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .