1

In bash script, below while loop is supposed to print 1 to 4 number.

But this one is resulting as an infinite loop.

COUNT=1

while [ $COUNT < 5 ];
do
  echo $COUNT
  COUNT=$(($COUNT+1))
done

Is there any fault in condition or syntax ? (I think so...)

Not a bug
  • 4,286
  • 2
  • 40
  • 80

1 Answers1

2

Use -lt instead of <:

COUNT=1; while [ $COUNT -lt 5 ]; do   echo $COUNT;   COUNT=$(($COUNT+1)); done
1
2
3
4

BASH syntax with [ doesn't recognize >, <, <=, >= etc operators. Check man test.

Even better is to use arithmetic processing in (( and )):

COUNT=1; while (( COUNT < 5 )); do echo $COUNT; ((COUNT++)); done

OR using for loop:

for (( COUNT=1; COUNT<5; COUNT++ )); do echo $COUNT; done
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • accepted...Yes this will solve problem, what is wrong in mine ? – Not a bug Feb 12 '14 at 11:19
  • 1
    Answer is accepted. more details will be appreciated :) – Not a bug Feb 12 '14 at 11:33
  • 1
    I guess I have already provided my recommendation i.e. use the last for loop and see how clean your code is. BASH has changed a lot so better adapt to modern syntax and ditch `[` command wherever possible. – anubhava Feb 12 '14 at 11:35