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

时间:2013-05-29 07:51:23

标签: bash shell if-statement

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

if 0; then
        echo yes
fi

这不起作用。它产生错误

./iffin: line 1: 0: command not found

我做错了什么?

3 个答案:

答案 0 :(得分:8)

使用

if true; then
        echo yes
fi

如果需要命令的返回码。 0不是命令。 true是一个命令。

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

您可能需要查看test命令以获取更复杂的条件逻辑。

if test foo = foo; then
        echo yes
fi

AKA

if [ foo = foo ]; then
        echo yes
fi

答案 1 :(得分:3)

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

 if (( 0 )) ; then
     echo Never echoed
 else
     echo Always echoed
 fi

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

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

答案 2 :(得分:0)

好吧,来自bash手册页:

if list; then list; [ elif list; then list; ] ... [ else list; ] fi

  The if list is executed.  If its exit status is zero, the then list is executed.
  Otherwise, each elif list  is  executed  in  turn, and if its exit status is zero,
  the corresponding then list is executed and the command completes.
  Otherwise, the else list is executed, if present.
  The exit status is the exit status of the last command executed,
  or zero if no condition tested true.

这意味着执行if的参数以获取返回代码,因此在您的示例中,您尝试执行显然不存在的命令0

命令truefalsetest存在的是什么,它们也被别名为[。它允许为if s编写更复杂的表达式。请阅读man test了解详情。