You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Joachim Ansorg edited this page Nov 15, 2021
·
6 revisions
-n doesn't work with unquoted arguments. Quote or use [[ ]].
Problematic code:
if [ -n$var ]
thenecho"var has a value"elseecho"var is empty"fi
Correct code:
In POSIX:
if [ -n"$var" ]
thenecho"var has a value"elseecho"var is empty"fi
In bash/ksh:
if [[ -n$var ]]
thenecho"var has a value"elseecho"var is empty"fi
Rationale:
When $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 [.