Unix for Mac OS X 10.4 Tiger: Visual QuickPro Guide (2nd Edition)

Doing Arithmetic and Using Expressions

It is frequently useful to have a script add two numbers together, or perform multiplication, division, or other arithmetic. The Bourne shell itself does not provide built-in arithmetic functions. Instead, it uses the standard Unix expr command to evaluate expressions .

The expr command sees expressions as a set of three arguments consisting of two arguments with an operator between them, such as

3 + 4

or

$x $y

Table 9.2 lists the operators you are most likely to use with expr . Read the man page ( man expr ) for the complete list. The math operators supported by expr work only on integers and give only integers as resultsno decimal places. See the sidebar "Floating-Point Math" for notes about doing this type of calculation.

Table 9.2. Math Operators for Use with expr

All numerical values must be integers. See the expr man page for other operators.

E XPRESSION

M EANING

$a + $b

Returns the sum of $a and $b .

$a - $b

Subtracts $b from $a .

$a \* $b

Returns the product of $a times $b . (You must escape the * with a backslash.)

$a / $b

Divides $a by $b .

$a % $b

Returns the remainder after dividing $a by $b .

Try the following task at a shell prompt before you try it in a script.

To evaluate an expression:

To add something to an existing variable:

Категории