Rob Avery IV
Rob Avery IV

Reputation: 3730

shell - Compare a string to a variable(string or number)

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 "".

Upvotes: 0

Views: 467

Answers (1)

Anton Kovalenko
Anton Kovalenko

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

Related Questions