8

My code looks something like this:

VAR=""

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

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" = "" ]?

  • 3
    == is incorrect syntax, but works in many shells (presumably because it's muscle memory to anyone using other languages). You should be using =. – l0b0 Jul 6 '15 at 11:42
  • @l0b0 copied the == from somewhere. My mistake. – Minix Jul 6 '15 at 11:47
5

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.

  • 5
    I though for sure that [ "$VAR" = "" ] was wrong because if the contents of $VAR were to start with a hyphen then it would lead to a syntax error, for example if $VAR contains -z then it would expand to [ -z = "" ] — would that test if = is empty (which it isn't) and then treat "" as an extraneous argument? But I cannot seem to make it fail that way now that I try it after reading your answer! I've been using contructs like [ "x$VAR" = "xfoo" ] to guard against special characters in $VAR for decades, perhaps unnecessarily! – Celada Jul 6 '15 at 12:09
  • @Celada: I think your point is true for the rare shells where test is not a builtin. – Basile Starynkevitch Jul 6 '15 at 12:17
  • 1
    I think that regarding expansions shell built-ins should behave the same way as external commands. Did not you confuse it with keywords like [[ in bash? They are really different. --- I do not observe any special behaviour regarding the variable expansion with the test build-in of bash. – pabouk Jul 6 '15 at 15:42
  • I tested with zsh – Basile Starynkevitch Jul 6 '15 at 18:02
  • @Celada actually, you are right, there are just so many things that could go wrong using [ "$VAR" = "" ] that is safer to use -z instead. – Braiam Jul 6 '15 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.