2

I am learning Shell Scripting and i got stuck that in most languages like C,C++, 0 means false and 1 means true, but in below shell script I am not able to understand, how the output is generated

if [ 0 ]
then
    echo "if"
else
    echo "else"
fi

No matter what i write inside if block like instead of 0, I tried 1,2,true,false it is always running if condition. How this works in shell scripting. And what shell script returns when the expression inside if statement is false.

1

2 Answers 2

4

It is always executing if part because this condition:

[ 0 ]

will always be true as it checks if the string between [ and ] is not null/empty.

To correctly evaluate true/false use:

if true; then
   echo "if"
else
   echo "else"
fi
Sign up to request clarification or add additional context in comments.

2 Comments

what will this expression return [ 10 -gt 100 ] because the string is not empty.
10 -gt 100 is a valid shell test condition and it will evaluate to false
2

There are no booleans in Bash. But here are some examples that are interpreted falsy:

  • Empty value: ""
  • Program exiting with non-zero code

A 0 as in your example is not falsy, because it's a non-empty value.

An example with empty value:

if [ "" ]
then
    echo "if"
else
    echo "else"
fi

An example with non-zero exit code (assuming there's no file named "nonexistent"):

if ls nonexistent &> /dev/null
then
    echo "if"
else
    echo "else"
fi

Or:

if /usr/bin/false
then
    echo "if"
else
    echo "else"
fi

Or:

if grep -q whatever nonexistent
then
    echo "if"
else
    echo "else"
fi

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.