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:
- Changing
==to-eq. - Surrounding
$varwith"". - Putting a
spaceinside""to make it" ". - Different combinations of 1-3
I want to be able to compare a string variable (empty or not) with "".
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 (
-npredicate which test for non-emptiness):if [ -n "$var" ]; then...Double quotes around
$varare required.