OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Arithmetic Expansion

The shell allows arithmetic to be performed by expansion. This allows us to use the shell prompt as a calculator:



[me@linuxbox ~]$ echo $((2 + 2))

4

[me@linuxbox ~]$ echo $((2 + 2))

4


Arithmetic expansion uses the form:

$((expression))

where expression is an arithmetic expression consisting of values and arithmetic opera- tors.

Arithmetic expansion only supports integers (whole numbers, no decimals), but can per- form quite a number of different operations. Here are a few of the supported operators:


Table 7-1: Arithmetic Operators

Operator Description

+ Addition


image

- Subtraction


image

* Multiplication


image

/ Division (but remember, since expansion only supports integer arithmetic, results are integers).


image

% Modulo, which simply means, “ remainder.”


image

** Exponentiation


image


Spaces are not significant in arithmetic expressions and expressions may be nested. For example, to multiply 5 squared by 3:



[me@linuxbox ~]$ echo $(($((5**2)) * 3))

75

[me@linuxbox ~]$ echo $(($((5**2)) * 3))

75


Single parentheses may be used to group multiple subexpressions. With this technique, we can rewrite the example above and get the same result using a single expansion in- stead of two:



[me@linuxbox ~]$ echo $(((5**2) * 3))

75

[me@linuxbox ~]$ echo $(((5**2) * 3))

75


Here is an example using the division and remainder operators. Notice the effect of inte- ger division:



[me@linuxbox ~]$ echo Five divided by two equals $((5/2))

Five divided by two equals 2

[me@linuxbox ~]$ echo with $((5%2)) left over.

with 1 left over.

[me@linuxbox ~]$ echo Five divided by two equals $((5/2))

Five divided by two equals 2

[me@linuxbox ~]$ echo with $((5%2)) left over.

with 1 left over.


Arithmetic expansion is covered in greater detail in Chapter 34.


Top OS Cloud Computing at OnWorks: