Skip to content

Files

Latest commit

 

History

History
48 lines (31 loc) · 1.12 KB

SC2244.md

File metadata and controls

48 lines (31 loc) · 1.12 KB

Pattern: Missing use of explicit -n to check non-empty string

Issue: -

Description

[ "$var" ] is equivalent to [ -n "$var" ] and checks whether the string is non-empty.

Users more familiar with other languages are therefore often surprised to learn that [ "$var" ] is true when var=false or var=0.

Adding the explicit -n helps clarify that this is a string comparison, and not related to any concept of boolean values or comparisons as it is in most languages.

Example of incorrect code:

if [ "$1" ]
then
  echo "True"
fi

Example of correct code:

# Check if $1 is empty or non-empty
if [ -n "$1" ]
then
  echo "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" ]

Exceptions

If you are familiar with the semantics of [, you can ignore this suggestion.

Further Reading