Are [ "$VAR" = "" ] and [ -z "$VAR" ] always equivalent?

My code looks something like this:


while [ -z "$VAR" ]; do
  VAR=$( command | grep "important_string" )

So I want to poll the output of command, until the important_string appears and put into $VAR.

Is there any functional difference between [ -z "$VAR" ] and [ "$VAR" = "" ]?

Asked By: Minix


Yes they ( [ -z "$VAR" ] and [ "$VAR" = "" ] …) are equivalent. Both are testing for emptiness of $VAR (e.g. when it is not bound, or set to an empty string).

As commented by Celada, bad things might happen when using [ "$VAR" = "" ] if VAR is some valid test (e.g. if VAR is -z), in particular when [ (or test) is not a shell builtin. But on bash or zsh the [ is a builtin and that does not seem to be an issue. You could use [ "x$VAR" = "x" ] for your test. See test(1)

Of course, I am assuming some POSIX shell or something similar.

Perhaps -z might be slightly faster (but you should not care about microseconds in shell scripts) and you might find = to perhaps be more readable.

Answered By: Basile Starynkevitch
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.