Parenthesis in expr arithmetic: 3 * (2 + 1)
Another way to use
$ let a="3 * (2 + 1)" $ printf '%s\n' "$a" 9
As @Stéphane Chazelas pointed out, in
bashyou should use
((...))to do arithmetic over
For portability, use
$((...))like @Bernhard answer.
+1 Even more readable! I posted my question+answer just thinking it would be helpful for my fellow Linux users, but now I am getting a lot of benefit from the other answers :-)
There's no reason to be using `let`. It's not any more standard or portable than `(( a = 3 * (2 + 1) ))` (both come from `ksh` and are only available in ksh, bash and zsh) and it's less legible or easy to quote. Use `a=$((3 * (2 + 1)))` to be portable.
I'm not saying it's wrong, I'm just saying it should not be used as there are better alternatives (one for legibility `((a = 3 * (2 + 1) ))`, one for portability `a=$((3 * (2 + 1)))`), so it's not a note against you or your answer but against it being the selected answer and top-scorer.
I have always used ```a=1 $[a+2]``` or ```a=1 b=2 $[a+b]```. Is their reason to avoid that syntax?