mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Updated SC2157 (markdown)
14
SC2157.md
14
SC2157.md
@@ -1,11 +1,12 @@
|
|||||||
## Argument to implicit -n is always true due to literal strings.
|
## Argument to implicit -n is always true due to literal strings.
|
||||||
|
(Or: Argument to -z is always false due to literal strings. )
|
||||||
|
|
||||||
### Problematic code:
|
### Problematic code:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
if [ "$foo " ]
|
if [ "$foo " ]
|
||||||
then
|
then
|
||||||
echo "this is always true"
|
echo "this is always true because of the trailing space"
|
||||||
fi
|
fi
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -20,9 +21,16 @@ fi
|
|||||||
|
|
||||||
### Rationale:
|
### Rationale:
|
||||||
|
|
||||||
Since `[ str ]` checks that the string is non-empty, the space inside the quotes in the problematic code causes the test to always be true, since a string with a space can not be empty.
|
Since `[ str ]` and `[ -n str ]` check that the string is non-empty, any literal characters in the string -- including a space character like in the example -- will cause the test to always be true.
|
||||||
|
|
||||||
|
Equivalently, since `[ -z str ]` checks that the string is empty, any literal character in the string will cause the test to always be false.
|
||||||
|
|
||||||
|
Double check the string: you may have added trailing characters, or bad quotes or syntax. Some examples include:
|
||||||
|
|
||||||
|
* `[ "$foo " ]` like in the example, where the space becomes part of the string
|
||||||
|
* `[ "{$foo}" ]` instead of `[ "${foo}" ]`, where the `{` becomes part of the string
|
||||||
|
* `[ "$foo -gt 0" ]` instead of `[ "$foo" -gt "0" ]`, where the `-gt` becomes part of the string
|
||||||
|
|
||||||
Sometimes this is also caused by overquoting an example, e.g. `[ "$foo -gt 0" ]`, which is always true for the same reason. The intention here was `[ "$foo" -gt 0 ]`.
|
|
||||||
|
|
||||||
### Exceptions:
|
### Exceptions:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user