From badedce7e84b3382b98b48b020704c2bcdc00f34 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Sat, 12 Oct 2019 19:54:36 -0700 Subject: [PATCH] Created SC2255 (markdown) --- SC2255.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SC2255.md diff --git a/SC2255.md b/SC2255.md new file mode 100644 index 0000000..97b1a7c --- /dev/null +++ b/SC2255.md @@ -0,0 +1,29 @@ +## `[ ]` does not apply arithmetic evaluation. Evaluate with `$((..))` for numbers, or use string comparator for strings. + +### Problematic code: + +```sh +[ 2*3 -eq array[i] ] +``` + +### Correct code: + +```sh +[ $((2*3)) -eq $((array[i])) ] +``` + +### Rationale: + +When using `[[ .. ]]` with numerical comparators (`-eq`, `-lt`, etc), the value on either side will be evaluated as an arithmetic expression. This means that `2*3` will be evaluated to `6`, and `x` will be evaluated to the contents of the variable `$x`. + +When using `[ .. ]`, this does not happen. `2*3` and `x` will both be considered invalid numbers. Instead, use e.g. `$((2*3))` to evaluate the expression before passing it to `[ .. ]`. + +Alternatively, if the expression should be considered a string, quote the expression and use a string comparison operator like `=` and `!=`. + +### Exceptions: + +None + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file