Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 240
Tyilo Avatar asked May 30 '11 18:05

Tyilo


People also ask

Can you use if statements in Bash script?

If statements (and, closely related, case statements) allow us to make decisions in our Bash scripts. They allow us to decide whether or not to run a piece of code based upon conditions that we may set.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.


1 Answers

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.

like image 69
Chen Levy Avatar answered Nov 15 '22 06:11

Chen Levy