Arithmetic operations using ((
When using bash and some other advanced shells, we can 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
. If you want to write it on a shell script, you need to add a dollar sign before the parentheses:
#!/bin/bash echo $(( 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...