Skip to content

Files

Latest commit

 

History

History
55 lines (40 loc) · 998 Bytes

SC2070.md

File metadata and controls

55 lines (40 loc) · 998 Bytes

Pattern: Use of -n with unquoted argument

Issue: -

Description

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 [.

Example of incorrect code:

if [ -n $var ]
then
  echo "var has a value"
else
  echo "var is empty"
fi

Example of correct code:

In POSIX:

if [ -n "$var" ]
then
  echo "var has a value"
else
  echo "var is empty"
fi

In bash/ksh:

if [[ -n $var ]]
then
  echo "var has a value"
else
  echo "var is empty"
fi

Further Reading