为什么在 shell 脚本中 "if 0;" 不起作用?

7
我写了以下shell脚本,只是为了检查我是否理解使用if语句的语法:
if 0; then
        echo yes
fi

这个不起作用。它会产生错误。
./iffin: line 1: 0: command not found

我做错了什么?

2
当您在shell提示符处键入“0”时会发生什么?您从中得出什么结论? - Jens
3个回答

10
if true; then
        echo yes
fi

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

Bash 手册对此并没有太多解释,但在这里:http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

如果需要更复杂的条件逻辑,您可能需要查看 test 命令。

if test foo = foo; then
        echo yes
fi

又称

if [ foo = foo ]; then
        echo yes
fi

5

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

 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

1
从1970年开始,可移植的方法是使用 if test -ne 0; then ...。带有 (()) 的算术表达式是一种花哨的新发明,属于渐进式特性主义 :-) 有一个名为 checkbashisms 的程序可以避免可移植性陷阱。 - Jens

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判断。阅读man test获取更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接