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?
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
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.
$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.
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.
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
'!'
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With