在 if 语句 (Bash) 中执行代码

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

Executing code in if-statement (Bash)

bashif-statement

提问by Tyilo

New question:

新问题:

I can't do this (Error: line 2: [: ==: unary operator expected):

我不能这样做(错误:)line 2: [: ==: unary operator expected

if [ $(echo "") == "" ]
then
    echo "Success!"
fi

But this works fine:

但这工作正常:

tmp=$(echo "")
if [ "$tmp" == "" ]
then
    echo "Success!"
fi

Why?

为什么?

Original question:

原问题:

Is it possible to get the result of a command inside an if-statement?

是否可以在 if 语句中获取命令的结果?

I want to do something like this:

我想做这样的事情:

if [ $(echo "foo") == "foo" ]
then
    echo "Success!"
fi

I currently use this work-around:

我目前使用这个解决方法:

tmp=$(echo "foo")
if [ "$tmp" == "foo" ]
then
    echo "Success!"
fi

回答by Chen Levy

The short answer is yes-- You can evaluate a command inside an ifcondition. The only thing I would change in your first example is the quoting:

简短的回答是肯定的——您可以在if条件内评估命令。在你的第一个例子中,我唯一要改变的是引用:

if [ "$(echo foo)" == "foo" ]
then 
    echo "Success"'!'
fi
  • Note the funny quote for the '!'. This disables the special behavior of !inside an interactive bash session, that might produce unexpected results for you.
  • 请注意'!'. 这会禁用!交互式 bash 会话内部的特殊行为,这可能会给您带来意想不到的结果。


After your update your problem becomes clear, and the change in quoting actually solves it:

更新后,您的问题变得清晰,引用中的更改实际上解决了它:

The evaluation of $(...)occurs before the evaluation of if [...], thus if $(...)evaluates to an empty string the [...]becomes if [ == ""]which is illegal syntax.

的评估$(...)发生在 的评估之前if [...],因此如果$(...)评估为空字符串,则[...]成为if [ == ""]非法语法。

The way to solve this is having the quotes outside the $(...)expression. This is where you might get into the sticky issue of quoting inside quoting, but I will live this issue to another question.

解决这个问题的方法是在$(...)表达式之外加上引号。这是您可能会遇到内部引用引用的棘手问题的地方,但我会将这个问题解决到另一个问题。