Search code examples
bashunset

unset variable check in bash


I have two variables declared but unset:

__var1=
__var2=

Now I set __var2 to have some value:

__var2=1

When I try to do a check like this:

[ -z "$__var1" -a -z "$__var2" ] || echo "Both missing!"

I am getting that message Both missing!. But that's incorrect.

Why is that? And how to do a proper check, to see if both of them are missing?


Solution

  • Your code prints "Both missing!" if it's not true (||) that both (-a) variables are empty (-z). You want to print the message if that IS true. Do that like this:

    [ -z "$__var1" -a -z "$__var2" ] && echo "Both missing!"
    

    I don't recall ever seeing a version of bash or test (what sh uses to evaluate the same expressions) without -z or -a, so as far as I know the above will work on any Unix-like system you're likely to find.