To calculate two variables in bash, we can use the $((...)) operator to perform arithmetic operations.

For example, suppose we have two variables, a and b, and we want to calculate the sum of a and b. We can use the following syntax:

ab=$((a + b))

This calculates the sum of a and b and stores the result in the ab variable.

$((...)) operator can be used to perform other arithmetic operations, such as:

  • subtraction

  • multiplication

  • division.

  • For example:

result=$((a - b))  # Subtract b from a
result=$((a * b))  # Multiply a and b
result=$((a / b))  # Divide a by b
Note:

Note that the $((...)) operator only supports integer arithmetic, so if we need to perform floating-point arithmetic - we need to use a tool like bc.

Divide two variables in bash

a=4;
b=2;
echo $((a / b))

The result from this operation is:

2

awk to calculate two variables

As an alternative solution we can use the command: awk. The following example shows the usage of awk command to multiple or sum two bash variables:

awk -v a=5 -v b=2 'BEGIN { print  ( a * b ) }'
awk -v a=5 -v b=2 'BEGIN { print  ( a + b ) }'

The result of these commands is:
10
7