Parenthesis in expr arithmetic: 3 * (2 + 1)

  • expr does not seem to like parenthesis (used in mathematics to explicit operator priority):

    expr 3 * (2 + 1)
    bash: syntax error near unexpected token `('
    

    How to express operator priority in bash?

  • cuonglm

    cuonglm Correct answer

    6 years ago

    Another way to use let bash builtin:

    $ let a="3 * (2 + 1)"
    $ printf '%s\n' "$a"
    9
    

    Note

    As @Stéphane Chazelas pointed out, in bash you should use ((...)) to do arithmetic over expr or let for legibility.

    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.

    @StéphaneChazelas: Updated my answer!

    I have always used ```a=1 $[a+2]``` or ```a=1 b=2 $[a+b]```. Is their reason to avoid that syntax?

    @Gordon: The bash man page says "The old format $[expression] is deprecated and will be removed in upcoming versions of bash."

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM