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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16808282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:32:07  来源:igfitidea点击:

Why does "if 0;" not work in shell scripting?

bashshellif-statement

提问by MYV

I wrote the following shell script, just to see if I understand the syntax to use if statements:

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

if 0; then
        echo yes
fi

This doesn't work. It yields the error

这不起作用。它产生错误

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

what am I doing wrong?

我究竟做错了什么?

回答by Philip Couling

use

if true; then
        echo yes
fi

if expects the return code from a command. 0is not a command. trueis a command.

如果期望来自命令的返回代码。0不是命令。 true是一个命令。

The bash manual doesnt say much on the subject but here it is: http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

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

You may want to look into the testcommand for more complex conditional logic.

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

if test foo = foo; then
        echo yes
fi

AKA

又名

if [ foo = foo ]; then
        echo yes
fi

回答by choroba

To test for numbers being non-zero, use the arithmetic expression:

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

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

It makes more sense to use variables than literal numbers, though:

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

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

回答by dmedvinsky

Well, from the bashman page:

好吧,从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.

Which means that argument to ifgets executed to get the return code, so in your example you're trying to execute command 0, which apparently does not exist.

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

What does exist are the commands true, falseand test, which is also aliased as [. It allows to write more complex expressions for ifs. Read man testfor more info.

确实存在的是命令true, falseand test,它也别名为[。它允许为ifs编写更复杂的表达式。阅读man test更多信息。