How to Divide Two Numbers in Bash [8 Easy Ways]

To divide two numbers in Bash use the following methods:

  1. Divide two integer variables x and y using expr command:
    $(expr $x / $y)
  2. Divide two variables and capture result of division using let command:
    let result=$x/$y
  3. Divide two integer numbers using arithmetic expansion:
    $(($x / $y))
  4. Divide two numbers up to desired precision using printf:
    printf "%.<precision>f" $((10**<precision>*$x/$y))e-<precision>
  5. Divide floating point numbers using bc command:
    result= "scale=<precision>; $x / $y" | bc
  6. Divide two numbers using awk command:
    $(awk "BEGIN {print $x / $y}")
  7. Use Python in Bash to divide numbers:
    $(python3 -c "print($x / $y)")
  8. Perl command for division in Bash:
    $(perl -e "print $x/$y")

Now, I am going to discuss each of the above methods in detail. Stay tuned.

1. Divide Two Variables Using the “expr” command

The expr command can be used to divide two integer variables. Here’s an example:

#!/bin/bash

# Define variables
x=10
y=2

# Use expr to perform division
result=$(expr $x / $y)
# Print the result
echo "Result of division: $result"
EXPLANATION

This Bash script defines two variables x and y, with values 10 and 2 respectively. It then utilizes the expr command to perform an integer division of x by y.

Dividing two variables using expr commandThe expr command, when used for division, provides only the integer portion of the result. For instance, if you divide 5 by 2, the expected result is 2.5. However, the expr command would yield 2.Result of division while using expr commandThe most important thing to note here is that I have placed a space before and after the division operator. If you remove these spaces, the expr command returns the string without performing the division.Spacing before and after division operator in expr commandIn addition, the expr command does not support floating point arithmetic. This means that the divisor and the dividend cannot be floating point numbers.Floating point number issue in expr command

2. Divide Two Integer Numbers Using “let” Command

The let command can perform division on the shell variable as well as the variables within the context of the command itself. Let’s see how it performs division on shell variables:

#!/bin/bash

x=100
y=25
let result=$x/$y
# Print the result
echo "Result of division: $result"
EXPLANATION

Here, x=100 and y=25. The let command divides x by y and stores the result of the division in the result variable.

Dividing two numbers using let commandUpon execution, the result of division 4 is as shown in the above image.

Additionally, variables x and y can be set in a single line using the let command like below:Defining variables within let command

3. Division of Two Numbers Using Arithmetic Expansion

Arithmetic expansion “$((expression))” can handle arithmetic operations, including division. To divide number a by b, use the expression $((a/b)). Here’s a simple and clear example:

#!/bin/bash

x=100
y=25
echo "Result of division: $(($x / $y))"
EXPLANATION

The script initializes variables x and y with values 100 and 25, respectively. It then uses arithmetic expansion to calculate and print the result of dividing x by y.

Division using arithmetic expansionWhen executed, the script outputs “Result of division: 4” to the terminal, representing the division of 100 by 25.

Arithmetic expansion provides the integer portion of the result only even if the result of division contains a fraction part. For instance, when 5 is divided by 2, it returns 2, not 2.5.Integer result of arithmetic expansion

NOTE: Arithmetic expansion cannot divide floating point numbers. This means that the divisor, or the dividend, cannot be a floating point number, even if the division result is an integer.

4. Calculating Division Up to Fixed Decimal Points Using “printf” Command

The printf command can be used to get around the limitations of arithmetic expansion. For example, if you divide 5 by 2, you won’t get the whole result of 2.5 using the arithmetic expansion only. However, printf with format specifier is capable of capturing the result of a division up to certain decimals.

The general syntax is:
printf "%.<precision>f\n" $((10**<precision> * <numerator>/<denominator>))e-<precision>
Let me explain the syntax using the following code:

printf "%.2f\n" $((10**2*5/2))e-2
EXPLANATION

$((10**2*5/2)) performs arithmetic expansion. First, 10 raised to the power of 2, which is 100. Then 100 is multiplied by 5, yielding 500. Finally, 500 is divided by 2, resulting in 250.

In $((10**2*5/2))e-2, the result of arithmetic expansion is multiplied by e-2. e-2 represents multiplying the preceding value by 10 to the power of -2. In this case, it means dividing the preceding value by 100. So, 250e-2 is equivalent to 2.50.

The printf “%.2f\n” statement specifies a format for printing. %.2f specifies that the number should be formatted as a floating point with two decimal places.

printf command for division in bash
NOTE: One can specify a precision value in the syntax to print the result up to a specific number of decimals.

5. Division of Floating Point Numbers Using “bc” Command

If you are trying to divide two floating point numbers don’t worry. Here comes the bc command. This command can divide integers as well as floating-point numbers. For that, you need to write the expression as a string and pass it to the bc command.

#!/bin/bash

x=100
$ y=-8.5
result= "scale=4; $x / $y" | bc
echo "Result of division: $result"
EXPLANATION

The variables x and y contain values 100 and -8.5 respectively. “scale=4; $x / $y” indicates a division operation with a precision of 4 decimal places. The string is piped to the bc command, which evaluates the expression and outputs the result.

bc command for division in bashUpon execution, the program divides 100 by -8.5 and prints the result up to four decimal places which is -11.7647.

NOTE: It is essential to use double quotation marks in the “scale=4; $x / $y” statement. Double quotation allows the shell to expand and access variables. On the other hand, a single quotation prevents the shell from expanding variables. Additionally, you can change the scale value to get the division up to the desired number of decimal points.

6. Divide Two Numbers Using “awk” Command

The awk command is popular for its text-processing utility. But it also handles arithmetic calculations. To perform division using this command, write the mathematical expression as a string within the BEGIN block, such as “BEGIN {print 5 / 2}”. Let’s see an example of that:

#!/bin/bash
# Define the numbers you want to divide
a=10
b=3

# Use awk for division
result=$(awk "BEGIN {print $a / $b}")

# Print the result
echo "Result of division: $result"
EXPLANATION

The program utilizes the awk command to perform division on two numbers, a and b. Here, a is set to 10 and b is set to 3. The awk command divides the number a by b The BEGIN block is used to provide the expression to the awk command.

awk command for division in BashAs you can see, the program prints the results of division 3.33333 (up to five decimal points by default).

7. Using Python Programming Language

One can use Python for division if it’s already installed in the system. python2 and python3 commands allow users to use Python version 2 and version 3 functionalities in Bash. Let’s see how to employ Python 3 for division in the Bash shell:

#!/bin/bash

# Define the numbers
a=10
b=2

# Perform division using Python
result=$(python3 -c "print($a / $b)")

# Print the result
echo "Result of division: $result"
EXPLANATION

The program uses Python for the division of two Bash variables a and b. The division is performed using the python3. The -c option allows to run Python utilities. The Python command, “print($a / $b)”, calculates the result of dividing a by b.

Division in Bash using PythonAfter execution, the program shows that the result of 10 divided by 2 is 5.0.

Python supports floating point numbers. So numerator and denominator of a division can be floats. Additionally, it allows users to set the precision of the result. Look at the following line of code:

python3 -c 'x=20.5; y=2.0; print("{:.2f}".format(x/y))'
# Output: 10.25

Format result of division in Bash

Here, "{:.2f}" format specifier in print("{:.2f}".format(x/y) used to display the result of x/y with two decimal places.

Python may not be installed in your system. Run the following command to install python3:

sudo apt-get install python3

8. Using “perl” Command

The perl one-liner with -e option allows users to perform the division of floating point numbers and customize the precision of the result as needed. Use the following command to do that:

perl -e '$x=22.0; $y=7.0; printf("%.6f\n", $x/$y)'

Perl command for division in BashIn this example, "%.6f\n" is used to format the result of division up to six decimal places. You can adjust the precision by changing the number inside the format specifier.

How to Calculate Remainder in Bash

The remainder or modulo (%) operator is used to calculate the remainder of a division in Bash. For example, $((5%2)) returns 1 because 5 / 2 is 2 with a remainder of 1. Let’s see how it works:

#!/bin/bash

# Define the numbers
a=10
b=3

# Calculate remainder
remainder=$((a % b))
# Print the result
echo "Remainder of $a divided by $b is: $remainder"
EXPLANATION

The script calculates the remainder of dividing the number a by b using the modulus operator (%). The values of a and b are defined as 10 and 3, respectively. The expression $((a % b)) computes the remainder of the division.

Calculating remainder in BashAfter running the program, it shows the remainder 1 as the remainder of the division 10/3 is 1.

How to Handle Division by Zero Error in Bash

When performing division, you might not know that the denominator is 0. But in bash, if you’re dividing by 0, you’ll get a “division by 0” error.Division by zero issue in BashTo handle this error it is wise to check the divisor variable using an if block:

#!/bin/bash

dividend=10
divisor=0
# Check if the divisor is zero before performing the division
if [ $divisor -eq 0 ]; then
echo "Error: Division by zero is not allowed."
else
result=$((dividend / divisor))
echo "Result: $result"
fi
EXPLANATION

The script begins by setting the variables dividend and divisor to the values 10 and 0, respectively.

It uses the if statement to determine if the divisor is zero. If the divisor is indeed zero, the script outputs a warning message indicating that division by zero is not allowed.

Otherwise, within the else block, the script calculates the result of dividing the dividend by the divisor using the arithmetic expansion and prints the result.

Checking division by zero using if blockHere the dividend is 10 but the divisor is zero. So the warning of the if block is displayed as you can see in the image above.

Conclusion

In conclusion, there are multiple methods available for performing division in Bash. Once you are sufficiently familiar with these methods, you can choose the one that best suits your task. I hope this article helps you understand the different approaches to division in Bash.

People Also Ask

How to round up or floor the result of division in Bash?

By default arithmetic expansion provides the floored result of a division. For example, The exact result of 7 by 3 is 2.33333…, but the arithmetic expansion $((7/3)) gives the floored result of 2.

On the other hand, to round up the result add the remainder of the division with the result of the division like the following script:

# Example: Divide 10 by 3 and round the result
#!/bin/bash
x=10
y=3
rounded_result=$(( (x / y) + (x % y > 0) ))
echo "Rounded Result: $rounded_result"

How can I Divide a specific column of numbers in Bash?

To awk command is useful for dividing a particular column of data in a file. Suppose you have a data file named data.txt with three columns of values. If you wish to divide the numbers in the third column by 1024 while keeping the rest of the columns unchanged, you can use the awk command.

#data.txt

-450  1526.64  1205.00
-60.4  1507.84  1205.36
15.89  1535.96  2281.44
17.89  1538.96  2281.40
19.89  1542.60  2282.08
21.90  1545.96  2282.32

To do so, use the following code. It processes each line in the file, extracts all fields, divides the third field by 1024, and then prints the formatted result to the terminal:

awk '{printf "%s\t%s\t%.2f\n", $1, $2, $3/1024}' data.txt

If you want to replace the original data.txt file with the modified data, you can use the following command:

awk '{printf "%s\t%s\t%.2f\n", $1, $2, $3/1024}' data.txt > temp && mv temp data.txt

How to divide the output of a command in Bash?

To divide the output of a command first capture the output in a variable using command substitution. Then use any methods of division available in Bash. Let’s say you have a file named file.txt. Now, you want to count the total number of lines in the file and divide it by 2:

lines= $(cat file | wc -l)
div=$lines/2
echo "Result: $div"

How do you divide values in two columns from different files in Bash?

To divide the values of two columns from different files, you can use a combination of commands such as paste or awk. Here’s an example assuming two files, file1.txt and file2.txt, with values arranged in a column:
#file1.txt
10.2
20
11.5
#file2.txt
9
5
3.33
Now divide the values of file1.txt by the values of file2.txt using the following code:

result=$(paste file1.txt file2.txt | awk '{printf "%.2f\n", $1/$2}')
echo "Result: $result"

Calculating division of values from two different filesThis command uses paste to merge the two files side by side and then uses awk to perform the division operation.

Related Articles


<< Go Back to Arithmetic Operators in Bash | Bash Operator | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment