简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM