Skip to content. | Skip to navigation

Navigation

You are here: Home / Support / Guides / Scripting / Bash / Arithmetic

Personal tools

Arithmetic

Sums in the shell

expr considered Bad

Many scripts will have expressions of the form:

var=`expr 1 + 1`

and even some horrors such as:

var=`expr 1 + \`expr 1 + 1\``

Can anyone even read that?

We shouldn't be doing that, Bash can do Arithmetic. By having the shell do the arithmetic we can avoid launching a subprocess and because we can do sensible things with parenthesis we can avoid hideous quoting nightmares.

$(( ... ))

The equivalent of the expr above is:

var=$(( 1 + 1 ))

ie.

$(( *some arithmetic expression* ))

some arithmetic expression can be pretty C-like (see the Arithmetic page for details) and variables can be referenced in a C-style fashion, ie. without the leading $:

% i=0
% var=$(( ++i ))
% echo $i, $var
1, 1

Caveats

You can use shell variables in these expressions:

% i=0
% var=$(( $i + 1 ))
% echo $i, $var
0, 1

But take care with some arithmetic operators as Parameter Expansion occurs before Arithmetic Expansion:

% i=0
% var=$(( $i++ ))
bash: 0++ : syntax error: operand expected (error token is "+ ")

Here, $i was expanded before the arithmetic started so the arithmetic looked like:

% var=$(( 0++ ))

which is clearly rubbish.

(( ... )) and let ...

These two are standalone commands which do arithmetic. Which is fine.

They do, however, cause you a problem if you are handling errors with the ERR trap. If the expression (or assignment with let) has the value 0 then they both fail (and return a non-zero exit status).

The semantic is the same as C in that 0 is the false case: 1 > 0 is true; 0 > 1 is false.

Document Actions