Arithmetic operations using ((

When using bash and some other advanced shells, we may make use of the (( )) notation to simplify mathematical operations with scripts.

Simple math

The double parenthesis construct in bash allows for arithmetic expansion. Using this in the simplest format, we can easily carry out integer arithmetic. This becomes a replacement for the let built-in. The following examples show the use of the let command and the double parenthesis to achieve the same result:

$ a=(( 2 + 3 ))
$ let a=2+3

In both cases, the a parameter is populated with the sum of 2 + 3.

Parameter manipulation

Perhaps, a little more useful to us in scripting is the C-style parameter manipulation that we can include using the double parenthesis. We can often use this to increment a counter within a loop and also put a limit on the number of times the loop iterates. Consider the following code:

$ COUNT=1
$ (( COUNT++ ))
echo $COUNT

Within this example, we first set COUNT to 1 and then we increment it with the ++ operator. When it is echoed in the final line, the parameter will have a value of 2. We can see the results in the following screenshot:

Parameter manipulation

We can achieve the same result in long-hand by using the following syntax:

$ COUNT=1
$ (( COUNT=COUNT+1 ))
echo $COUNT

This of course allows for any increment of the COUNT parameter and not just a single unit increase. Similarly, we can count down using the -- operator, as shown in the following example:

$ COUNT=10
$ (( COUNT-- ))
echo $COUNT

We start using a value of 10, reducing the value by 1 within the double parenthesis.

Tip

Note that we do not use the $ to expand the parameters within the parenthesis. They are used for parameter manipulation and as such we do not need to expand parameters explicitly.

Standard arithmetic tests

Another advantage that we can gain from these double parentheses is with the tests. Rather than having to use -gt for greater than we can simply use >. We can demonstrate this in the following code:

$(( COUNT > 1 )) && echo "Count is greater than 1"

The following screenshot demonstrates this for you:

Standard arithmetic tests

It is this standardization, both in the C-style manipulation and tests, that make the double parenthesis so useful to us. This use extends to both, the command line and in scripts. We will use this feature extensively when we look at looping constructs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.248.37