5

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
Tyilo
  • 28,998
  • 40
  • 113
  • 198

1 Answers1

6

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.

Chen Levy
  • 15,438
  • 17
  • 74
  • 92
  • I've just tested this code, and it still starts new shell. After I exit shell, Success is printed out. Using GNU bash 4.1.5 – bbaja42 May 30 '11 at 18:51
  • What if i need to use a command that requires me to escape a variable inside this? Example `str="123 456 789"; if [ "$(someCommand $str)" == "foo" ]; then echo "Success!"; fi` and someCommand only checks the first param – Tyilo May 30 '11 at 18:56
  • :( My bad, I've accidentally started new bash at start of script. Everything works correctly. :D – bbaja42 May 30 '11 at 19:04
  • @Tyilo, quoting with double quotes allows for evaluation of `$str` so your example should work, but preserving spaces might be a thornier issue: E.g. if `str="123 456 789"` (note the 2 spaces between "123" and "456"), in that case you might want to try `"$(someCommand "$str")"`. – Chen Levy Aug 06 '17 at 08:42