Re:Use the Unofficial Bash Strict Mode (Unless You Love Debu...
by stantona on Sunday March 20, 2016 @11:28AM
(#11323277)
The test command has certain rules depending on the number of arguments.
The most pertinent rule is:
For one argument, the expression is true if, and only if, the argument is not null.
In this case
[ -n $var ]
is the same as test -n $var
$var is not quoted, so when this command is run, word splitting occurs and therefore $var is null. Which there falls into the one argument rule above.Therefore, always quote your variables.
Re:Use the Unofficial Bash Strict Mode (Unless You Love Debu...
by ycmbntrthrwaway on Saturday March 19, 2016 @08:15AM
(#11318233)
> the reason is complex, I'll leave it as a puzzle for the reader
[ -n ]
is the same as test -n
In this case -n has no argument, so it cannot be parsed as "-n STRING", instead it is parsed as "STRING", where STRING is "-n", with the behaviour "True if string is not empty.".
Also, an unquoted variable that happens to be null will essentially vanish from the argument list of any command it's used with, which can cause another class of weird bugs. Consider the shell statement:
if [ -n $var ]; then
... which looks like it should execute the condition if $var is nonblank, but in fact will execute it even if $var is blank (the reason is complex, I'll leave it as a puzzle for the reader).
Setting IFS is a crutch that only partly solves the problem; putting double-quotes around variable references fully solves it.