0

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:

  1. Changing == to -eq.
  2. Surrounding $var with "".
  3. Putting a space inside "" to make it " ".
  4. Different combinations of 1-3

I want to be able to compare a string variable (empty or not) with "".

1
  • Which shell are you using? Commented Feb 15, 2013 at 16:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

To keep the same sense of the original test you'd want to use [ -z "$var" ] (-z: true if the argument is a zero-length string)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.