bash shell 脚本中的单行 if 语句不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9437375/
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-09 21:41:32  来源:igfitidea点击:

single-line if statement in a shell script not working

bashscriptingif-statement

提问by Alexander Bird

This is my code:

这是我的代码:

#!/bin/bash
cat input | ./prog > output && if[ "" != "" ]; diff output expected;

This then happens:

然后会发生这种情况:

$ ./run.sh
./run.sh: line 2: if[ no !=  ]: command not found
$

I thought that I could run if statements on one line? is that what the problem is?

我以为我可以在一行上运行 if 语句?这就是问题所在吗?

回答by Alexander Bird

it turns out that there needs to be a space between the ifand the [. Also, I put in the thenand fikeywords.

事实证明,if和之间需要有一个空格[。另外,我输入了thenfi关键字。

The following worked.

以下工作。

#!/bin/bash
cat input | ./prog > output && if [ "" != "" ]; then diff output expected; fi

EDIT:

编辑:

as commented below (and in another answer), this can elegantly be shortened to:

正如下面(以及在另一个答案中)所评论的,这可以优雅地缩短为:

cat input | ./prog > output && [ "" != "" ] && diff output expected

in which case I don't even have to remember any of the rules about how to use the ifconstruct :)

在这种情况下,我什至不必记住有关如何使用if构造的任何规则:)

回答by Ярослав Рахматуллин

drop the if. [] will spawn a new "command" and you can run diff or whatever after if it exits with 0 using && (run next if previous exits ok). here:

放弃如果。[] 将产生一个新的“命令”,如果它使用 && 以 0 退出,您可以运行 diff 或其他任何内容(如果前一个退出正常,则运行下一个)。这里:

echo lol &&  [ $((10-1)) -eq 9 ] && echo math\!

and your one-liner:

和你的单线:

#!/bin/bash
cat input | ./prog > output && [ "" != "" ] && diff output expected