为什么"如果0;" 不能在shell脚本中工作?

MYV*_*MYV 3 bash shell if-statement

我编写了以下shell脚本,只是为了了解我是否理解使用if语句的语法:

if 0; then
        echo yes
fi
Run Code Online (Sandbox Code Playgroud)

这不起作用.它产生错误

./iffin: line 1: 0: command not found
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Phi*_*ing 8

使用

if true; then
        echo yes
fi
Run Code Online (Sandbox Code Playgroud)

if期望从命令返回代码.0不是命令. true是一个命令.

bash手册对这个主题没有太多说明,但它是:http: //www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

您可能希望查看test命令以获得更复杂的条件逻辑.

if test foo = foo; then
        echo yes
fi
Run Code Online (Sandbox Code Playgroud)

AKA

if [ foo = foo ]; then
        echo yes
fi
Run Code Online (Sandbox Code Playgroud)


cho*_*oba 5

要测试数字是否为非零,请使用算术表达式:

 if (( 0 )) ; then
     echo Never echoed
 else
     echo Always echoed
 fi
Run Code Online (Sandbox Code Playgroud)

但是,使用变量比使用文字数字更有意义:

count_lines=$( wc -l < input.txt )
if (( count_lines )) ; then
    echo File has $count_lines lines.
fi
Run Code Online (Sandbox Code Playgroud)