Division in Bash

MD Aminul Islam Jul 12, 2022
Division in Bash

We need to perform numerical calculations for various purposes. We use division in our code for many purposes like finding the prime numbers, quotients, etc.

This article will show how we can perform division in Bash with necessary examples and explanations.

Division in Bash

The general syntax for division in Bash is:

$(( DIVIDEND/DIVISOR ))

A very simple example of a division is shared below:

echo "100 divided by 2 is: $(( 100/2 ))"

After running the above code, you will get the output below.

Output:

100 divided by 2 is: 50

Now, we are going to see two more examples on this topic.

A Basic Example of Division in Bash

In the below example, we performed a basic division. We take a number from the user and then divide it by two.

Below, we shared the code for the example:

read -p "Provide a number: " num
echo "Your result is: $(( num/2 ))"

Using the line read -p "Provide a number: " num, we took the user input. And using the line echo "Your result is: $(( num/2 ))", we divided the user input by two.

Here the part $(( num/2 )) performed the division operation. You will get the output below after you run the example code.

Output:

Provide a number: 12
Your result is: 6

An Advance Example of Division in Bash

This is a bit advanced example of our above example. In this example, we take both the dividend and divisor from the user and perform a division operation between them.

Below, we shared the code for our example:

read -p "Provide a number for the dividend: " dividend
read -p "Provide a number for the divisor: " divisor
echo "Calculated result is: $(( dividend/divisor ))"

In the above code, using the lines read -p "Provide a number for the dividend: " dividend and read -p "Provide a number for the divisor: " divisor, we take the user input for the dividend and divisor.

And using the line echo "Calculated result is: $(( dividend/divisor ))", we performed the division between the dividend and divisor. Here the part $(( dividend/divisor )) performed the division operation between the user input.

You will get this output after you run the example code.

Output:

Provide a number for the dividend: 32
Provide a number for the divisor: 2
Calculated result is: 16

Please note that all the code used in this article is written in Bash. It will only be runnable in the Linux Shell environment.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Bash Math