One common task when working with variables in Bash is to divide two variables, which might look simple. However, when working on Bash, you must need to do it with care.
This article is a detailed guide to divide two variables in Bash with some examples of how to use this operation in your scripts.
How to Divide Two Variables in Bash
You can divide two variables in Bash using:
Method 1: Divide Two Variables in Bash Using the expr Command
The expr command in bash evaluates an expression and prints the result to the console. To divide two variables using the expr command, here is an example code:
# Declare variables
num1=8
num2=4
# Divide variables using expr command
result=$(expr $num1 / $num2)
echo "Result: $result"
In this example, we are using the expr command to divide the value of num1 by the value of num2, the result of the division is stored in the result variable, which is then printed to the console:
Method 2: Divide Two Variables in Bash Using the Double Parentheses
The double parentheses syntax is a shorthand way of performing arithmetic operations in Bash so to divide two variables using the double parentheses, here is an example code:
# Declare variables
num1=8
num2=4
# Divide variables using double parentheses syntax
result=$((num1 / num2))
echo "Result: $result"
Here, we are using the double parentheses syntax to divide the value of num1 by the value of num2, the result of the division is stored in the result variable, which is then printed to the console.
Conclusion
Dividing two variables in Bash is a common task when working with numerical data. This article discussed two common methods for dividing two variables in Bash. By using the expr command and the double parentheses syntax, you can quickly and easily divide two variables in Bash scripts.