From b55ab54d90e1e54d1c1300e83d306714880fc6b0 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Fri, 28 Dec 2018 19:26:37 -0800 Subject: [PATCH] Created SC2244 (markdown) --- SC2244.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 SC2244.md diff --git a/SC2244.md b/SC2244.md new file mode 100644 index 0000000..adc589c --- /dev/null +++ b/SC2244.md @@ -0,0 +1,46 @@ +## Prefer explicit -n to check non-empty string (or use =/-ne to check boolean/integer). + +### Problematic code: + +```sh +if [ "$1" ] +then + echo "True" +fi +``` + +### Correct code: + +```sh +# Check if $1 is empty or non-empty +if [ -n "$1" ] +then + echo "True, $1 is a non-empty value" +fi + +# Check instead if $1 is true or false, as in Java +[ "$1" = "true" ] + +# Check instead if $1 is non-zero or zero, as in C +[ "$1" -ne 0 ] + +# Check instead if $1 is defined (even if just assigned the empty string) or undefined +[ "${1+x}" = "x" ] + +``` + +### Rationale: + +`[ "$var" ]` is equivalent to `[ -n "$var" ]` and checks whether the string is non-empty. + +Users more familiar with other languages are therefore often surprised to learn that `[ "$var" ]` is true when `var=false` or `var=0`. + +Adding the explicit `-n` helps clarify that this is a string comparison, and not related to any concept of boolean values or comparisons as it is in most languages. + +### Exceptions: + +If you are familiar with the semantics of `[`, you can [[ignore]] this suggestion with no ill effects. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file