Does not work as expected unless I use quotes... Why?
From man test
(and see also posix test):
-n STRING
the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING
the length of STRING is zero
When $1
is empty, then [ -n $1 ]
executes [ -n ]
. [ STRING ]
is equivalent to [ -n STRING ]
, so [ -n ]
is equivalent to [ -n -n ]
, and because -n
is nonzero string, [
succeeds.
Check your scripts with http://shellcheck.net
Unquoted variable expansion undergo word splitting and filename expansion!
Research Difference between single and double quotes in Bash and When to wrap quotes around a shell variable? and https://mywiki.wooledge.org/Quotes
So I should ... always use double quotes?
As a rule of thumb you should always wrap expansions in double quotes.
So I should ... use double square brackets ... ?
The [[
is a bash extension not available in other shells, and from [[ documentation we know that: Word splitting and filename expansion are not performed on the words between the [[ and ]]
, so that's why there is no need to (but it does no harm) to double quote expansions between [[
. [[
is specially handled by the shell, it's a special builtin with special syntax.
When working in bash-specific script that will never be ported, you may prefer [[
over [
because it should be tiny bit faster faster.