Bash Division

In Bash scripting, division is a common arithmetic operation that allows you to calculate the quotient of two numbers. Bash offers multiple ways to perform division using arithmetic expansion, the expr command, and the bc command for handling floating-point numbers.

In this tutorial, we will explore these methods with detailed examples and scenarios.

For a quick overview of the Arithmetic Operations in Bash, you may refer Bash Arithmetic Operations.


Syntax for Division in Bash

There are several ways to perform division in Bash. Here is the syntax for the most commonly used methods:

Division using Arithmetic Expansion:

</>
Copy
$((a / b))

Division using expr:

</>
Copy
expr a / b

Division using bc (for floating-point division):

</>
Copy
echo "scale=2; a / b" | bc

Examples of Division in Bash

Let’s go through different examples to see how division can be performed using these methods.


1 Bash Division Using Arithmetic Expansion

Arithmetic expansion is a simple way to perform division in Bash using the $((...)) syntax. However, it only works with integers and does not support floating-point numbers.

example.sh

</>
Copy
#!/bin/bash

# Define two integers
num1=20
num2=5

# Perform division
result=$((num1 / num2))

# Display the result
echo "The result of dividing $num1 by $num2 is $result."

Output