执行code的if语句(击) [英] Executing code in if-statement (Bash)

查看:149
本文介绍了执行code的if语句(击)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新问题:

我不能做到这一点(错误: 2号线:[:==:一元运算符预期

 如果[$(回声)==]
然后
    回声成功了!
科幻

但是,这工作得很好:

  TMP = $(回声)
如果[$ TMP==]
然后
    回声成功了!
科幻

为什么?

原题:

时有可能得到一个if语句中的命令的结果?

我想要做这样的事情:

 如果[$(回声富)==富]
然后
    回声成功了!
科幻

我目前使用此解决方法:

  TMP = $(回声富)
如果[$ TMP==富]
然后
    回声成功了!
科幻


解决方案

简短的答案是 - 您可以评估范围内的命令的如果的条件。我会在你的第一个例子中更改的唯一一件事就是报价:

 如果[$(回声富)==富]
然后
    回声成功'!
科幻


  • 注意对搞笑引号'!。这将禁用的一个交互式的bash会话中,可能会产生意外的结果对你的特殊行为。


您更新后您的问题变得清晰,并在实际报价变化解决它:

$的评价(...)发生的评价之前,如果[...] ,因此,如果 $(...)的计算结果为空字符串 [...] 变成如果[==] 这是非法的语法。

解决这个问题的方法是具有 $(...)前pression之外引号。在这里,您可能进入里面引用引用的艰难的问题,但我会住这个问题的另一个问题。

New question:

I can't do this (Error: 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?

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. 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.

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.

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.

这篇关于执行code的if语句(击)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆