From 0c60c8138280f087c8ad0a1ef14a2e215c8b5d9b Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Sun, 22 Aug 2021 20:00:31 -0700 Subject: [PATCH] Created SC2304 (markdown) --- SC2304.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 SC2304.md diff --git a/SC2304.md b/SC2304.md new file mode 100644 index 0000000..57f344c --- /dev/null +++ b/SC2304.md @@ -0,0 +1,30 @@ +## `*` must be escaped to multiply: `\*`. Modern `$((x * y))` avoids this issue. + +### Problematic code: + +```sh +result=$(expr 2 * 3) +``` + +### Correct code: + +```sh +# Modern, efficient, POSIX standard approach +result=$(( 2 * 3 )) + +# Older, slower approach +result=$(expr 2 \* 3) +``` +### Rationale: + +When using `expr`, each argument is expanded the same way as for any other command. This means that `expr 2 * 3` will turn into `expr 2 Desktop Documents Downloads Music Pictures 3` depending on the files in the current directory, causing an error like `expr: syntax error: unexpected argument ‘Desktop’` + +The best way to avoid this is to avoid `expr` and instead use `$((..))` instead. If you for any reason prefer the 200x slower, heavyweight process of forking a new process, you can escape the `*`. Both ways are demonstrated in the correct example. + +### Exceptions: + +None + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file