简体   繁体   English

如何在Shell脚本中使用if else

[英]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 我正在学习Shell Scripting,但在大多数语言(例如C,C ++)中,我陷入了困境,0表示false,1表示true,但是在下面的Shell脚本中,我无法理解输出是如何生成的

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. 不管我在if块中写什么而不是0,我都尝试1,2,true,false,如果条件始终运行。 How this works in shell scripting. 这在Shell脚本中如何工作。 And what shell script returns when the expression inside if statement is false. 当if语句中的表达式为false时,shell脚本将返回什么。

It is always executing if part because this condition: 它总是在执行if一部分,因为这种情况:

[ 0 ]

will always be true as it checks if the string between [ and ] is not null/empty. 将始终为true,因为它会检查[]之间的字符串是否不是null / empty。

To correctly evaluate true/false use: 要正确评估对/错使用:

if true; then
   echo "if"
else
   echo "else"
fi

There are no booleans in Bash. 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. 在您的示例中, 0不是虚假的 ,因为它是一个非空值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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