When using bash and some other advanced shells, we may make use of the (( ))
notation to simplify mathematical operations with scripts.
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
.
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...