Tyilo
Tyilo

Reputation: 30102

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

Upvotes: 5

Views: 7060

Answers (1)

Chen Levy
Chen Levy

Reputation: 16378

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.

Upvotes: 6

Related Questions