3

I want to test multiple variables to see if they are empty. So I did the following:

if [ test -z "$VAR1" ] || [ test -z "$VAR2" ]
then
   echo "Empty!"
fi

However, it doesn't work. The output is:

[: -z: binary operator expected
[: -z: binary operator expected

What have I done wrong? The code above works fine if I leave out the OR (||) condition.

2
  • 1
    if [[ -z "$VAR1" || -z "$VAR2" ]]; then ... fi should work in bash Commented Sep 17, 2019 at 15:03
  • 1
    [ is test, not part of the if statement's syntax. Type help [ and help test at the prompt for more information. Commented Sep 17, 2019 at 15:14

2 Answers 2

5

Use either brackets or the test command, don't use both. Either of the following will work:

if [ -z "$VAR1" ] || [ -z "$VAR2" ]
then
   echo "Empty!"
fi

Or:

if test -z "$VAR1" || test -z "$VAR2"
then
   echo "Empty!"
fi

In some older shells [ was just an alias for the test command. You could even miss out the closing ] (or add it after test) and everything would be fine. Nowadays, on bash this will give a syntax error. However, the two (correct) syntaxes are still functionally equivalent and can be used interchangeably but not at the same time.

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

Comments

2

You should either use test, or [; they are synonymous, except [ requires a ] as last argument.

[ -z "$VAR1" ] || [ -z "$VAR2" ]

or

test -z "$VAR1" || test -z "$VAR2"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.