From 06d214a1d6d08bc154c672c022cc2fb028ddb1cb Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Thu, 28 Jun 2018 11:46:05 -0700 Subject: [PATCH] Created SC2099 (markdown) --- SC2099.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 SC2099.md diff --git a/SC2099.md b/SC2099.md new file mode 100644 index 0000000..f4f55c8 --- /dev/null +++ b/SC2099.md @@ -0,0 +1,39 @@ +## Use `$((..))` for arithmetics, e.g. `i=$((i + 2))` + +### Problematic code: + +```sh +i=3 +i=i + 2 +``` + +### Correct code: + +```sh +i=3 +i=$((i + 2)) +``` + +### Rationale: + +Unlike most languages, variable assignments in shell scripts are space sensitive and (almost) always assign strings. + +To evaluate a mathematical expressions, use `$((..))` as in the correct code: + + i=$((i + 2)) # Spaces are fine inside $((...)) + +In the problematic code, `i=i + 2` will give an error `+: command not found` because the expression is interpreted similar to something like `LC_ALL=C wc -c` instead of numerical addition: + + Prefix assignment Command Argument + LC_ALL=C wc -c + i=i + 2 + +### Exceptions: + +If you wanted to assign a literal string, quote it: + + game_score="0 - 2" + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file