Bash scripting — 3 — Performing Arithmetic Operation in shell script — The Linux GURUS

Shujat Husain
2 min readJan 13, 2020

--

In this tutorial, we will learn about performing arithmetic operations in shell scripts & also about the logical/boolean operators. So let’s first start with the all the arithmetic operations as well as the arithmetic, boolean operators that can be used in Linux,

Recommended Read: How to install MySQL on Ubuntu Also Read: Bash Scripting-4- Using conditionals (if else in shell script)

Now let’s see some examples of performing arithmetic operation in shell script,

Addition & Subtraction

echo “ Adding $num1 & $num2, output is $[$num1+$num2]”

echo “Subtracting $num2 from $num3, the output is $[$num3-$num2]”

Multiplication & Division

echo “ Multipying $num1 & $num2, output is $[$num1*$num2]”

echo “Dividing $num2 by $num3, the output is $[$num3/$num2]”

Performing a Floating point arithmetic operations in shell script

Now when we perform some arithmetic operations like division, we might get the answer as floating point number. For example,

echo “Dividing $num1 by $num2, the output is $[$num1/$num2]”

So the output, in this case, would be ‘2.5’ but we would get the output as ‘2’. So how to work this out, how to get the right answer. To accomplish this floating point arithmetic operation, we need to use ‘bc’ command.

bc command or bash calculator which allows us to perform floating point arithmetic operations. Syntax for using the bc command is,

Here scale=3 means the number of decimal places up to which division will be performed. So the above mentioned script will change to,

echo “Dividing $num1 by $num2, the output is $(echo “scale=3; $num1/$num2″|bc) “

Now the output for the script will be,

Dividing 5 by 2, the output is 2.500

So with this, we will end this tutorial on performing Arithmetic Operation in shell script. These bash scripting tutorials will continue with our coming posts as well. Please do send us your suggestions, questions or queries using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

TheLinuxGURUS are thankful for your continued support.

Originally published at https://thelinuxgurus.com on January 13, 2020.

--

--

Shujat Husain
Shujat Husain

Written by Shujat Husain

A TechEenthusiat who likes all new technologies & Gaming. Most of all love to write about Cloud & DevOPs & have my own blog as well (https://linuxtechlab.com).

No responses yet