From 76115d51a6e92851d73db66cdba28001f279ab67 Mon Sep 17 00:00:00 2001 From: koalaman Date: Wed, 14 Oct 2015 10:37:21 -0700 Subject: [PATCH] Created SC2170 (markdown) --- SC2170.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 SC2170.md diff --git a/SC2170.md b/SC2170.md new file mode 100644 index 0000000..41c370b --- /dev/null +++ b/SC2170.md @@ -0,0 +1,34 @@ +## Numerical -eq does not dereference in [..]. Expand or use string operator. + +### Problematic code: + +```sh +read -r n +if [ n -lt 0 ] +then + echo "bad input" +fi +``` + +### Correct code: + +```sh +read -r n +if [ "$n" -lt 0 ] +then + echo "bad input" +fi +``` +### Rationale: + +You are comparing a string value with a numerical operator, such as `-eq`, `-ne`, `-lt` or `-gt`. + +In `[[ .. ]]`, this would automatically dereference the string, looking to see if there are variables by that name. + +In `[ .. ]`, which you are using, the string is just treated as an invalid number. + +If you want to compare numbers, expand yourself (e.g. use `$var` instead of `var`). If you are trying to compare strings and not numbers, use `=`, `!=` `\<` or `\>` instead. + +### Exceptions: + +None. \ No newline at end of file