11. Arithmetic Expansion

Bash expands characters between the "$((...))" operator as an arithmetic expression. Arithmetic expressions operate on integer values:

echo $(( (1 + 2) / 2 ))
1

Inside arithmetic expansion variables are expanded by name only:

$ integer=2
$ echo $(( integer - 3 ))
-1

There is no need of the parameter expansion notation. Values of undeclared variables, the null value or values being not an integer are evaluated to 0:

$ unset eight
$ echo $(( 2 ** eight + word))
1

Octal values can be written by a leading "0":

$ echo $(( 010 ))
8

while hexadecimal values are prefixed by "0x":

echo $(( 0x10 ))
16

The operators and their precedence, associativity, and values are the same as in the C language. Variables can be incremented and decremented in prefix and postfix notation:

$ int=0
$ echo $(( ++int + int++ + --int + int--))
4

Exponentiation (**), multiplication (*), division (/), remainder (%), addition (+) and subtraction (-) can be done like with any calculator:

$ echo $(( 255%16 - 2*2**3 + 100/10**2 ))
0

Integers can be shifted bitwise to higher (<<) or lower values (>>):

$ echo $(( 8 << 2))
32

The relations greater (>), greater equal (>=), lower (<) and lower equal (<=) compare integers by size. A True value will be given by 1, a False by 0:

$  echo $(( 1 <  2 <= 3))
1

Even for the equality (==) and inequality (!=) operators:

$ echo $(( (1 != 2 ) == 1 ))
1

Values can be compared bitwise by the AND (&), exclusive OR (^) or OR (|) operators:

$ echo $(( (8 ^ 7) & 16 ))
0

or logically by the AND (&&) or OR (||) operators:

$ echo $(( ( 0 || 1 ) && 1 ))
1

Even the eternity operator exists:

$ echo $(( 1>0?1:0 ))
1

Last but not least assignments can be done (=, *=, /=, +=, -=, <<=, >>=, &=, ^= and |=). The operators returns their assigned values:

$ echo $(( int=99 ))
99

Arithmetic expansion is also nestable:

$ echo $(( $(echo $(( 1 + 2 ))) + $int + $(echo 1 + 2) ))
105