Doing Arithmetic in Your Shell Script
Problem
You need to do some simple arithmetic in your shell script.
Solution
Use $(( )) or let for integer arithmetic expressions.
COUNT=$((COUNT + 5 + MAX * 2)) let COUNT+=5+MAX*2
Discussion
As long as you keep to integer arithmetic, you can use all the standard (i.e., C-like)
operators inside of $(()) for arithmetic. There is one additional
operator—you can use ** for raising to a power, as in MAX=$((2**8))
, which yields 256.
Spaces are not needed nor are they prohibited around operators and arguments (though ** must be together) within a $(( )) expression. But you must not have spaces around the equals sign, as with any bash variable assignment. If you wrote:
COUNT = $((COUNT + 5)) # not what you think!
then bash will try to run a program named
COUNT and its first argument would be an equal
sign, and its second argument would be the number you get adding
5
to the value of $COUNT
. Remember not to put spaces around the
equal sign.
Another oddity to these expressions is that the $ that we normally put in front of a shell variable to say
we want its value (as in $COUNT
or
$MAX
) is not needed inside the
double parentheses. For example, $((COUNT +5
MAX * 2))
needs no dollar sign on the shell variables—in
effect, the outer $ applies to the entire expression.
We do need the dollar sign, though, if we are using a positional
parameter (e.g.,$2
) to distinguish it
from a numeric constant (e.g., “2”). Here’s an example:
COUNT=$((COUNT + $2 + OFFSET))
There is a similar ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.