Parenthesis in expr arithmetic: 3 * (2 + 1)
You can use the arithmetic expansion instead.
echo "$(( 3 * ( 2 + 1 ) ))"
9
In my personal opinion, this looks a bit nicer than using expr
.
From man bash
Arithmetic Expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$((expression))
The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic expansions may be nested.
The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs.
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.
There's no reason to be using expr
for arithmetic in modern shells.
POSIX defines the $((...))
expansion operator. So you can use that in all POSIX compliant shells (the sh
of all modern Unix-likes, dash, bash, yash, mksh, zsh, posh, ksh...).
a=$(( 3 * (2 + 1) ))
a=$((3*(2+1)))
ksh
also introduced a let
builtin which is passed the same kind of arithmetic expression, doesn't expand into something but returns an exit status based on whether the expression resolves to 0 or not, like in expr
:
if let 'a = 3 * (2 + 1)'; then
echo "$a is non-zero"
fi
However, as the quoting makes it awkward and not very legible (not to the same extent as expr
of course), ksh
also introduced a ((...))
alternative form:
if (( a = 3 * (2 + 1) )) && (( 3 > 1 )); then
echo "$a is non-zero and 3 > 1"
fi
((a+=2))
which is a lot more legible and should be used instead.
let
and ((...))
are only available in ksh
, zsh
and bash
. The $((...))
syntax should be preferred if portability to other shells is needed, expr
is only needed for pre-POSIX Bourne-like shells (typically the Bourne shell or early versions of the Almquist shell).
On the non-Bourne front, there are a few shells with built-in arithmetic operator:
csh
/tcsh
(actually the first Unix shell with arithmetic evaluation built-in):@ a = 3 * (2 + 1)
akanga
(based onrc
)a = $:'3 * (2 + 1)'
as a history note, the original version of the Almquist shell, as posted on usenet in 1989 had an
expr
builtin (actually merged withtest
), but it was removed later.