From 62ab4099c2158bf894ebb8290add93eb3f116e0e Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Wed, 29 Aug 2018 10:43:45 -0700 Subject: [PATCH] Updated SC2157 (markdown) --- SC2157.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/SC2157.md b/SC2157.md index 8df9804..c317db2 100644 --- a/SC2157.md +++ b/SC2157.md @@ -1,11 +1,12 @@ ## Argument to implicit -n is always true due to literal strings. +(Or: Argument to -z is always false due to literal strings. ) ### Problematic code: ```sh if [ "$foo " ] then - echo "this is always true" + echo "this is always true because of the trailing space" fi ``` @@ -20,9 +21,16 @@ fi ### 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: