In Bash, several arithmetic operators can be used to perform mathematical calculations. Here are the most common arithmetic operators:
-
Addition (
+): Adds two numbers.result=$((5 + 3)) # result is 8 -
Subtraction (
-): Subtracts the second number from the first.result=$((5 - 3)) # result is 2 -
Multiplication (
*): Multiplies two numbers.result=$((5 * 3)) # result is 15 -
Division (
/): Divides the first number by the second. Note that this performs integer division.result=$((5 / 2)) # result is 2 -
Modulo (
%): Returns the remainder of the division of the first number by the second.result=$((5 % 2)) # result is 1 -
Exponentiation (
**): Raises the first number to the power of the second number (available in Bash 4.0 and later).result=$((2 ** 3)) # result is 8
Using Arithmetic Operators
You can use these operators within the $(( )) syntax for arithmetic evaluation:
a=10
b=5
sum=$((a + b)) # Addition
difference=$((a - b)) # Subtraction
product=$((a * b)) # Multiplication
quotient=$((a / b)) # Division
remainder=$((a % b)) # Modulo
power=$((a ** b)) # Exponentiation
Summary
Bash supports various arithmetic operators, including addition, subtraction, multiplication, division, modulo, and exponentiation, which can be used for performing mathematical calculations in scripts.
