# Performing Math calculation in Bash

### Performing Math calculation in Bash

Hi Guys, this is my 4th tutorial in BASH Scripting series (other tutorials are HERE). In this tutorial we will be discussing about using mathematical operations in our scripts.

Learning to do Math in scripting is crucial feature as we must know how we manipulate numbers in BASH Scripting.

So, let’s get started ……

Firstly we should know various Arithmetic & Boolean operators that are used BASH scripting,

### Arithmetic Operators

+ – Addition, subtration
++ — Increment, decrement
* / % Multiplication, division, remainder
** Exponentiation

### Logical and Boolean Operators

<= >= < > Less than or equal, greater than or equal, less than, greater than
== != Equal, not equal
! Logical NOT
&& Logical AND
|| Logical OR

Now, let us see how we can use these in our scripts.

### Using Arithmetic Operations in scripts

In order to perform arithmetic operations in scripts, we use “ \$ [operation]”.

Example

#!/bin/bash
# this script shows arithmetic operations
var1=10
var2=20
var3=5
echo “Addition of \$var1 & \$var2 is \$[\$var1 + \$var2]”
echo “Subtraction of \$var1 & \$var2 is \$[\$var1 – \$var2]”

Same way we can use other operators also. Now, let me point out a limitation with using  Arithmetic operations in BASH scripting. Let’s take an example,

#!/bin/bash
# this script shows arithmetic operations limitation
var1=15
var2=6
var3=\$[\$var1 / \$var2]
echo \$var3

Result of above script should be “2.5” but rather it shows only “2” . That is because BASH only supports integer arithmetic operations & doesn’t support floating point arithimetic, which is a huge limitation.

But this can be resolved i.e. we can do floating point arithmetic operations using bc command.

### bc Command

bc or bash calculator is a programming language that allows us to perform floating point arithmetic operations. We can either use bc directly by typing “bc ” in our BASH terminal or we can also use bc inside our scripts. Syntax for using bc in scripts is variable=\$(echo “options; expression” | bc)

Example

#!/bin/bash
# this script shows floating point arithmetic operations
var1=\$(echo “scale=4; 13.84 / 6” | bc)
echo The answer is \$var1

Here, “scale” shows number of decimal places upto which calculations are to be done. This script is a good example of how we can use bc to do floating point calculations in BASH.

This completes our tutorial on Mathematical operation in BASH scripting. I will be back with next tutorial soon. Feel free to send your comments/queries. 