Bash Arithmetic
Arithmetic is calculation with whole numbers inside a script. Bash performs it inside $(( )), which is called arithmetic expansion.
Add two numbers
The expression inside $(( )) is worked out first. Echo then prints the result, 7.
echo $((3 + 4))Division drops the remainder
Seven divided by two gives 3, because the remainder is dropped. The % line shows that remainder separately, and the last line multiplies.
echo $((7 / 2))
echo $((7 % 2))
echo $((6 * 3))Use variables in a calculation
Variables inside $(( )) need no dollar sign. Bash reads price and quantity and multiplies them.
price=4
quantity=3
echo $((price * quantity))Example
count=0
count=$((count + 1))
echo $count
count=$((count + 1))
echo $count
total=$((count * 10))
echo $totalKey points
- Arithmetic expansion starts with $(( and ends with )).
- The symbols + - * / % mean add, subtract, multiply, divide, and remainder.
- Division keeps only the whole part and drops the remainder.
- The % symbol gives the remainder left after division.
- Variables work inside $(( )) without a $ before their names.
- Storing $((count + 1)) back into count counts up by one.
In this example, count starts at 0. The next line adds one and stores 1 back into count, and the echo prints it. The same counting step runs again, so count becomes 2 and prints. The last calculation multiplies count by ten and stores 20 in total, which the final echo prints.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does echo $((10 % 3)) print?