There is a subreddit /r/nononoyes for videos of things that look like they’ll go horribly wrong, but amazingly turn out ok.
[ -z $var ] would belong there.
It’s a bash statement that tries to check whether the variable is empty, but it’s missing quotes. Most of the time, when dealing with variables that can be empty, this is a disaster.
Consider its opposite,
[ -n $var ], for checking whether the variable is non-empty. With the same quoting bug, it becomes completely unusable:
These issues are due to a combination of word splitting and the fact that
[ is not shell syntax but traditionally just an external binary with a funny name. See my previous post Why Bash is like that: Pseudo-syntax for more on that.
The evaluation of
[ is defined in terms of the number of argument. The argument values have much less to do with it. Ignoring negation, here’s a simplified excerpt from POSIX test:
|# Arguments||Action||Typical example|
|1||True if $1 is non-empty||
|2||Apply unary operator $1 to $2||
|3||Apply binary operator $2 to $1 and $3||
Now we can see why
[ -n $var ] fails in two cases:
When the variable is empty and unquoted, it’s removed, and we pass 1 argument: the literal string “-n”. Since “-n” is not an empty string, it evaluates to true when it should be false.
When the variable contains
foo bar and is unquoted, it’s split into two arguments, and so we pass 3: “-n”, “foo” and “bar”. Since “foo” is not a binary operator, it evaluates to false (with an error message) when it should be true.
Now let’s have a look at
[ -z $var ]:
|“”||True: is empty||True||1 arg: is “-z” non-empty|
|“foo”||False: not empty||False||2 args: apply
|“foo bar”||False: not empty||False (error)||3 args: apply “foo’ to -z and bar|
It performs a completely wrong and unexpected action for both empty strings and multiple arguments. However, both cases fail in exactly the right way!
In other words,
[ -z $var ] works way better than it has any possible business doing.
This is not to say you can skip quoting of course. For “foo bar”,
[ -z $var ] in bash will return the correct exit code, but prints an ugly error in the process. For ” ” (a string with only spaces), it returns true when it should be false, because the argument is removed as if empty. Bash will also incorrectly pass
var="foo -o x" because it ends up being a valid test through code injection.
The moral of the story? Same as always: quote, quote quote. Even when things appear to work.
ShellCheck is aware of this difference, and you can check the code used here online.
[ -n $var ] gets an angry red message, while
[ -z $var ] merely gets a generic green quoting warning.