-n
is always true due to literal strings.(Or: Argument to -z is always false due to literal strings. )
if [ "$foo " ]
then
echo "this is always true because of the trailing space"
fi
if [ "$foo" ]
then
echo "correctly checks value"
fi
Since [ str ]
and [ -n str ]
check that the
string is non-empty, any literal characters in the string -- including a
space character like in the example -- will cause the test to always be
true.
Equivalently, since [ -z str ]
checks that the string is
empty, any literal character in the string will cause the test to always
be false.
Double check the string: you may have added trailing characters, or bad quotes or syntax. Some examples include:
[ "$foo " ]
like in the example, where the space
becomes part of the string[ "{$foo}" ]
instead of [ "${foo}" ]
,
where the {
becomes part of the string[ "$foo -gt 0" ]
instead of
[ "$foo" -gt "0" ]
, where the -gt
becomes part
of the stringNone.
ShellCheck is a static analysis tool for shell scripts. This page is part of its documentation.