Weird (infinite) while loop with code before "do"

Viewed 47

I teach in a Sec. School and a student in my class has come with this code, asking me why the loop never ends.

1 counter=1  
2 while (( counter < 3 ))  
3 echo $LINENO: $counter  
4 do 
5    ((counter++))
6 done
7 echo $LINENO: The end

This results in a infinite loop, and I really do not know why :-(

Running this code through bashdb it shows that the test on line 2 does not affect the flow: lines 3 and 5 are executed, then the flow returns to line 2 to do the test again, execute line 4 and 5, and the loop never jumps past "done" in line 6.

The script keeps printing the counter value and incrementing it.

If I transpose lines 3 and 4 the loop behaves as usual and stops after 2 iterations.

I have tested this code in Bash v. 4 on both OSX and Linux.

Any idea about this loop behavior? Thanks you all. :-)

1 Answers

The condition used in the while loop is everything between while and do. In this case, the condition includes line 3 (the echo) which returns 0 every time. The result of the comparison is ignored and the exit status of the echo is used, as documented in help while:

while: while COMMANDS; do COMMANDS; done

Execute commands as long as a test succeeds.

Expand and execute COMMANDS as long as the final command in the while COMMANDS has an exit status of zero.

Related