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 12, 2021
·
3 revisions
Prefer explicit -n to check non-empty string (or use =/-ne to check boolean/integer).
Problematic code:
if [ "$1" ]
thenecho"True"fi
Correct code:
# Check if $1 is empty or non-emptyif [ -n"$1" ]
thenecho"True, $1 is a non-empty value"fi# Check instead if $1 is true or false, as in Java
[ "$1"="true" ]
# Check instead if $1 is non-zero or zero, as in C
[ "$1"-ne 0 ]
# Check instead if $1 is defined (even if just assigned the empty string) or undefined
[ "${1+x}"="x" ]
Rationale:
[ "$var" ] is equivalent to [ -n "$var" ] and checks that a string is non-empty.
Users more familiar with other languages are often surprised to learn that [ "$var" ] is true when:
var=false
var=0
var=null
var=" "
Adding the explicit -n helps clarify that this is a string comparison, and not related to any concept of boolean values or "truthiness" as it is in most languages.
Exceptions:
If you are familiar with the semantics of [, you can ignore this stylistic suggestion with no ill effects.
Related resources:
Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!