From 3685488d3d408b08ce172a5a9c31f43159381212 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Sun, 30 Jul 2023 16:06:16 -0700 Subject: [PATCH] Created SC2324 (markdown) --- SC2324.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 SC2324.md diff --git a/SC2324.md b/SC2324.md new file mode 100644 index 0000000..a2e2f74 --- /dev/null +++ b/SC2324.md @@ -0,0 +1,49 @@ +## var+=1 will append, not increment. Use (( var += 1 )), declare -i var, or quote number to silence. + +### Problematic code: + +```sh +var=2 n=3 +var+=$n +``` + +### Correct code: + +In bash/ksh, use an `(( arithmetic context ))` + +```sh +(( var += n )) +``` + +or declare the variable as an integer type: + +```sh +declare -i var=2 +n=4 +var+=$n +``` + +For POSIX sh, use an `$((arithmetic expansion))`: + +```sh +var=$((var+n)) +``` + + +### Rationale: + +The problematic code attempts to add 2 and 3 to get 5. + +Instead, `+=` on a string variable will concatenate, so the result is 23. + +### Exceptions: + +If you *do* want to concatenate a number, for example to append trailing zeroes, you can silence the warning by quoting the number: + +```sh +var+="000" +``` + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file