1

I tried it with some example but it is not clear to me.

FIRST EXAMPLE

#!/bin/bash
i=0
while [ $i -lt 10 ]
do
    echo "$i"
    i=`echo "$i + 1" | bc`
done

output ===> 0,1,2,3,4,5,6,7,8,9

now when i executed while "while [ true ] " it gives the output as infinite loop //I agree//
but when i executed while "while [ false ] " again it gives the output as infinite loop. /I dont agree/

Can you please explain the second while loop? and how it is working actually?

while [ false ]    #give the infinite loop
while [ true ]     #give the infinite loop
while [ 0 ]        #give the infinite loop
while [ 1 ]        #give the infinite loop
while [ `ls` ]
while [ `echo 1` ] #give the infinite loop
while((0))         #loop not execute
while((1))         #give the infinite loop
6
  • 1
    First, do you know the difference between [] and (()) ? [] is a test operator. (()) arithmetic evaluator.
    – Vikyboss
    Feb 10 '16 at 17:46
  • what is return statement of "[ $i -lt 10 ]" if i=5 @Vikyboss
    – Tiger
    Feb 10 '16 at 17:50
  • 1
    When you evaluate a expression inside test operator [], it should return an exit code of 0 for the expression evaluating to true and non-zero if false. [ $i -lt 10 ] is saying i(5) is less than 10, so it returns an exit code of 0.
    – Vikyboss
    Feb 10 '16 at 17:52
  • 1
    I would suggest you to read man page of 'test' and 'bash'.
    – Vikyboss
    Feb 10 '16 at 17:53
  • if we write the script like while 1 do echo "hello" done while 0 do echo "hello" done
    – Tiger
    Feb 10 '16 at 18:04
2

In while [ false ] the false is neither a command nor a boolean value. The while expects a command but [ ... ] with no operators just checks for any non-empty string. Thus [ false ] is true. It is in this sense the same as [ faaaalseeee ].

What you meant is:

while true; do ...

while false; do ...
9
  • then how it execute...?? like c language "while(0)" --> it will never execute
    – Tiger
    Feb 10 '16 at 17:40
  • 2
    @Tiger I don't understand the question. Feb 10 '16 at 17:41
  • then what about this statement " echo [ $i -lt 10 ] "
    – Tiger
    Feb 10 '16 at 17:43
  • simply i want when while loop is execute and what is return statement of "[ $i -lt 10 ]" if i=5
    – Tiger
    Feb 10 '16 at 17:47
  • @Tiger Your first example does show that the exit code of [ 5 -lt 10 ] is zero (i.e. true). echo [ $i -lt 10 ] is just an echo statement, the [ $i -lt 10 ] part has no meaning other than a string (or rather: several strings). echo always exists with zero no matter what the output string is. Feb 10 '16 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.