Performing Math
Another feature crucial to any programming language is the ability to manipulate numbers. Unfortunately, for shell scripts this process is a bit awkward. There are two different ways to perform mathematical operations in your shell scripts.
The expr command
Originally, the Bourne shell provided a special command that was used for processing mathematical equations. The expr
command allowed the processing of equations from the command line, but it is extremely clunky:
$ expr 1 + 5
6
The expr
command recognizes a few different mathematical and string operators, shown in Table 11.1.
Table 11.1 The expr Command Operators
Operator | Description |
ARG1 | ARG2 |
Returns ARG1 if neither argument is null or zero; otherwise, returns ARG2 |
ARG1 & ARG2 |
Returns ARG1 if neither argument is null or zero; otherwise, returns 0 |
ARG1 < ARG2 |
Returns 1 if ARG1 is less than ARG2 ; otherwise, returns 0 |
ARG1 <= ARG2 |
Returns 1 if ARG1 is less than or equal to ARG2 ; otherwise, returns... |