mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Updated SC2070 (markdown)
12
SC2070.md
12
SC2070.md
@@ -1,4 +1,4 @@
|
|||||||
## Always true because you failed to quote. Use [[ ]] instead.
|
## -n doesn't work with unquoted arguments. Quote or use [[ ]].
|
||||||
|
|
||||||
### Problematic code:
|
### Problematic code:
|
||||||
|
|
||||||
@@ -13,10 +13,10 @@ fi
|
|||||||
|
|
||||||
### Correct code:
|
### Correct code:
|
||||||
|
|
||||||
In bash/ksh:
|
In POSIX:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
if [[ -n $var ]]
|
if [ -n "$var" ]
|
||||||
then
|
then
|
||||||
echo "var has a value"
|
echo "var has a value"
|
||||||
else
|
else
|
||||||
@@ -24,10 +24,10 @@ else
|
|||||||
fi
|
fi
|
||||||
```
|
```
|
||||||
|
|
||||||
In POSIX:
|
In bash/ksh:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
if [ -n "$var" ]
|
if [[ -n $var ]]
|
||||||
then
|
then
|
||||||
echo "var has a value"
|
echo "var has a value"
|
||||||
else
|
else
|
||||||
@@ -47,7 +47,7 @@ When `$var` is unquoted, a blank value will cause it to wordsplit and disappear.
|
|||||||
|
|
||||||
`[ 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 ]`.
|
`[ 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.
|
To fix this, either quote the variable, or (if your shell supports it) use `[[ -n $var ]]` which generally has fewer caveats than `[`.
|
||||||
|
|
||||||
### Exceptions:
|
### Exceptions:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user