Infinite while loop

what is the difference between while:,while true and while false?

Hi,

"while :" and "while true" - are the same.

"while false" - this would simply take you to the end of the while loop. I havent seen this being used. Does it serve any purpose ??

"while false" - this would simply take you to the end of the while loop. I haven't seen this being used. Does it serve any purpose ??

Thats what i was asking..:slight_smile:

'true' returns nothing successfully, while false returns nothing unsuccessfully. As a result, using 'while false' would only exit your loop rather quickly, while not executing the code beneath. 'while' and 'while true' vary in what the condition is for the loop. If nothing is passed to 'while' then it assumes 'while true'.

@atoponce

I hope i am getting it. But still could you provide an example to make this more clear.
Thanks in advance

$ true
$ echo $?
0
$ false
$ echo $?
1

That shows the exit code of "true" and "false". As you can see, they both do nothing. One returns a passing exit code, while the other returns a failing exit code. The "while" function wants an argument. It will continue parsing code inside the loop until the argument fails.

i="0"
while [ $i -lt 4 ]; do
  xterm &
  i=$[$i+1]
done

This piece of code will open four xterm windows. It will only open four, because we set our variable 'i' to 0 and increment it once per loop iteration. When it reaches the value of four, the while condition fails, and the code block will no longer be executed.

So, because "true" does nothing successfully, if you had "while true" in that code block, it would continue and continue to open xterm windows until you ran out of physical resources, and the box could no longer function.

Because "false" does nothing unsuccessfully, if you had "while false" in that code block, it would not even initialize the loop, and immediately exit without opening a single xterm window.

Thanks a lot.