chandradot99
chandradot99

Reputation: 3866

How to use if else in Shell Scripting

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.

Upvotes: 2

Views: 247

Answers (2)

anubhava
anubhava

Reputation: 784958

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

Upvotes: 4

janos
janos

Reputation: 124648

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

Upvotes: 2

Related Questions