Using expr, $(()), (())
For arithmetic,
expr
is archaic. Don't use it.*$((...))
and((...))
are very similar. Both do only integer calculations. The difference is that$((...))
returns the result of the calculation and((...))
does not. Thus$((...))
is useful inecho
statements:$ a=2; b=3; echo $((a*b)) 6
((...))
is useful when you want to assign a variable or set an exit code:$ a=3; b=3; ((a==b)) && echo yes yes
If you want floating point calculations, use
bc
orawk
:$ echo '4.7/3.14' | bc -l 1.49681528662420382165 $ awk 'BEGIN{print 4.7/3.14}' 1.49682
*As an aside, expr
remains useful for string handling when globs are not good enough and a POSIX method is needed to handle regular expressions.
expr is old, but it does have one limited use I can think of. Say you want to search a string. If you want to stay POSIX with grep, you need to use a pipe:
if echo november | grep nov
then
: do something
fi
expr can do this without a pipe:
if expr november : nov
then
: do something
fi
the only catch is expr works with anchored strings, so if you want to match after the beginning you need to change the REGEXP:
if expr november : '.*ber'
then
: do something
fi
Regarding (( ))
, this construct is not POSIX, so should be avoided.
Regarding $(( ))
, you do not have to include the dollar sign:
$ fo=1
$ go=2
$ echo $((fo + go))
3