Arithmetic

The Bourne Shell has no built in ability to do arithmetic calculations. In contrast the C Shell, the Korn Shell, and Bash all have such an ability. However, the Bourne Shell can make use of the external program expr to do such calculations.

The expr program accepts numeric arguments and the usual operators. It outputs on its standard output file the calculated results. Expr can use parenthesis to group expressions.

There are two things you must remember when using expr: First, since its taking things as arguments, spaces are significant on its command line. Second, since many of the arthmetic operators are special characters to the shell, you must quote things liberally.

For example

$ expr 2 \* 3
6
$ expr 10 / \( 2 + 3 \)
2
$

You might be tempted to do something like

$ expr "10 / ( 2 + 3 )"

It doesn't work because expr needs each operator and operand to be it's own argument. The double quotes makes everything one big argument.

Normally expr is used inside scripts. For example to increment the numeric value stored in the shell variable 'COUNT' do this:

$ COUNT=`expr $COUNT + 1`

Notice the use of back quotes to force expr's standard output back onto the command line where it can be used to redefine the value of COUNT.