简体   繁体   English

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

[英]Executing code in if-statement (Bash)

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

The short answer is yes -- You can evaluate a command inside an if condition.简短的回答是肯定的——您可以在if条件内评估命令。 The only thing I would change in your first example is the quoting:在您的第一个示例中,我唯一要更改的是引用:

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 session 中,这可能会给您带来意想不到的结果。

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.这是您可能会遇到引用内部引用的棘手问题的地方,但我将把这个问题放在另一个问题上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM