Reputation: 3730
I want to find out if the string variable is empty or not. I do this by comparing the variable to a literal empty string (""
).
Here is my code:
var=$1
if [$var == ""]; then
echo "\$var is $var"
fi
It gives me this error when $1
is ""
(No command line argument(s)):
./script.sh: line 5: [: ==: unary operator expected
When $1
has a value, it works fine.
I've tried the following things and they still have given me an error:
==
to -eq
.$var
with ""
.space
inside ""
to make it " "
.I want to be able to compare a string variable (empty or not) with ""
.
Upvotes: 0
Views: 467
Reputation: 21507
You should always have a space after the opening bracket ([
), because it's a command name.
The way to do it closest to your own: if [ "$var" = "" ]; then...
Another way to do it (-n
predicate which test for non-emptiness): if [ -n "$var" ]; then...
Double quotes around $var
are required.
Upvotes: 2