mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2070 (markdown)
46
SC2070.md
Normal file
46
SC2070.md
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
## Always true because you failed to quote. Use [[ ]] instead.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
if [ -n $var ]
|
||||||
|
then
|
||||||
|
echo "var has a value"
|
||||||
|
else
|
||||||
|
echo "var is empty"
|
||||||
|
fi
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
In bash/ksh:
|
||||||
|
|
||||||
|
if [[ -n $var ]]
|
||||||
|
then
|
||||||
|
echo "var has a value"
|
||||||
|
else
|
||||||
|
echo "var is empty"
|
||||||
|
fi
|
||||||
|
|
||||||
|
In POSIX:
|
||||||
|
|
||||||
|
if [ -n "$var" ]
|
||||||
|
then
|
||||||
|
echo "var has a value"
|
||||||
|
else
|
||||||
|
echo "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 use `[[ -n $var ]]` which has fewer caveats than `[`, or quote the variable.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
None
|
Reference in New Issue
Block a user