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)

Arithmetic Operators

Logical and Boolean Operators

+

Addition

<=

less than or equal to

substraction

>=

greater than or equal to

++

Increment

<

less than

Decrement

>

greater than

*

Multiplication

==

Equal to

/

Division

!=

not equal to

%

Remainder

!

logical NOT

**

Expornention

&&

logical AND

||

logical OR

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

Addition & Subtraction

#!/bin/bash

num1=10

num2=20

num3=40

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

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

Multiplication & Division

#!/bin/bash

num1=10

num2=20

num3=40

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,

#!/bin/bash

num1=5

num2=2

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,

# “scale=3; num1/num2 | bc

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

#!/bin/bash

num1=5

num2=2

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:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.