Chapter 6: Working with numbers
—
- Bash can do integer math, not decimal or fractional.
- Supports 6 operators,
+ - * / % ** -
$((...))- Is an Arithmetic Expansion, and returns the result of the mathematical operation. This does NOT modify the existing variable. -
((...))- Is an Arithmetic Evaluation and performs calculations and changes the values of existing variables. They do not provide any return value, but an exit status instead. - When a variable is referenced inside the double parentheses, whether for arithmetic expansion or arithmetic evaluation, it does not need to be prefaced with a dollar sign.
1 echo $((8 + 8))
2 # returns 16
3 a=3
4 ((a+=3))
5 echo $a # will return 6
6 ((a++))
7 echo $a # will return 7
We can use declare -i b=3 to tell Bash that the variable is an integer and not treat it as a string. It’s a good idea to use declare when we know the variables we use will be integers.
1 a=3
2 a=$a+2
3 # will print 3+2 as bash is treating the variable as a st\
4 ring
5 echo $a
6 declare -i b=3 # declare b as an integer
7 b=$b+2
8 # will return 5
9 echo $b
echo $RANDOM will return a pseudo-random value between 0 and 32,767. Use $(( 1 + $RANDOM%20)) to get a random number between 1 and 20.