简体   繁体   中英

Executing code in if-statement (Bash)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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