-n
doesn't work with unquoted arguments. Quote or use
[[ ]].if [ -n $var ]
then
echo "var has a value"
else
echo "var is empty"
fiIn POSIX:
if [ -n "$var" ]
then
echo "var has a value"
else
echo "var is empty"
fiIn bash/ksh:
if [[ -n $var ]]
then
echo "var has a value"
else
echo "var is empty"
fiWhen $var is unquoted, a blank value will cause it to
wordsplit and disappear. If $var is empty, these two
statements are identical:
[ -n $var ]
[ -n ][ string ] is shorthand for testing if a string is
empty. This is still true if string happens to be
-n. [ -n ] is therefore true, and by extension
so is [ -n $var ].
To fix this, either quote the variable, or (if your shell supports
it) use [[ -n $var ]] which generally has fewer caveats
than [.
None
ShellCheck is a static analysis tool for shell scripts. This page is part of its documentation.