HomeLinuxBash Fundamentals Collection #4: Arithmetic Operations

Bash Fundamentals Collection #4: Arithmetic Operations


You are able to do a whole lot of issues with bash scripts. Performing easy arithmetic operations with the variables is one among them.

The syntax for arithmetic operations within the bash shell is that this:

$((arithmetic_operation))

For instance you need to calculate the sum of two variables. You do it like this:

sum=$(($num1 + $$num2))

There isn’t a restriction on using white house contained in the (()). You should utilize $(( $num1+ $num2)), $(( $num1+ $num2 )) or $(( $num1+ $num2 )). All of it will work the identical.

Earlier than I talk about it intimately with examples, let me share the arithmetic operators it helps.

Primary arithmetic operators in Bash

Here is a listing of the arithmetic operators within the Bash shell.

Operator Description
+ Addition
Subtraction
* Multiplication
/ Integer division (with out decimal)
% Modulus division (solely the rest)
** Exponentiation (a to the facility b)

🚧

Bash doesn’t assist floating factors (decimals). You will have to make use of different instructions like bc to cope with them.

Addition and subtraction in bash

Let’s examine it by writing a script that takes two numbers from the person after which prints their sum and subtraction.

#!/bin/bash

learn -p "Enter first quantity: " num1
learn -p "Enter second quantity: " num2

sum=$(($num1+$num2))
sub=$(($num1-$num2))
echo "The summation of $num1 and $num2 is $sum"
echo "The substraction of $num2 from $num1 is $sub"

I imagine you’re accustomed to utilizing the learn command to settle for person enter in bash from the earlier chapter.

You must give attention to these two traces:

sum=$(($num1+$num2))
sub=$(($num1-$num2))

Save this script as sum.sh and run it. Give it some inputs and test the end result.

Example of addition and subtraction in Bash shell script

Multiplication in bash

Let’s transfer to multiplication now.

Here is a pattern script that converts kilometers into meters (and troubles US readers :D). For reference, 1 kilometer is the same as 1000 meters.

#!/bin/bash

learn -p "Enter distance in kilometers: " km
meters=$(($km*1000))

echo "$km KM equals to $meters meters"

Save the script as multi.sh, give it execute permission and run it. Here is a pattern output:

Multiplication in bash script

Appears good, no? Let’s transfer on to division.

Division in bash scripts

Let’s examine division with a quite simple script:

#!/bin/bash

num1=50
num2=5

end result=$(($num1/$num2))

echo "The result's $end result"

You’ll be able to simply guess the end result:

The result's 10

That is nice. However let’s change the numbers and attempt to divide 50 by 6. Here is what it exhibits as end result:

The result's 8

However that is not appropriate. The right reply needs to be 8.33333.

That is as a result of bash solely offers with integers by default. You want extra CLI instruments to deal with floating factors (decimals).

The most well-liked software is bc which is sort of a strong calculator language to cope with mathematical operations. Nevertheless, you do not want to enter element for now.

You need to ‘echo’ the arithmetic operation to bc by way of pipe:

echo "$num1/$num2" | bc -l

So, the earlier script is modified into:

#!/bin/bash

num1=50
num2=6

end result=$(echo "$num1/$num2" | bc -l)

echo "The result's $end result"

And now you get the end result:

The result's 8.33333333333333333333

Discover the end result=$(echo "$num1/$num2" | bc -l), it now makes use of the command substitution that you just noticed in chapter 2 of this sequence.

The -l choice hundreds normal math library. By default, bc will go as much as 20 decimal factors. You’ll be able to change the size to one thing smaller on this manner:

end result=$(echo "scale=3; $num1/$num2" | bc -l)

Let’s examine some extra examples of floating factors in bash.

Dealing with floating factors in bash scripts

Let’s modify the sum.sh script to deal with floating factors.

#!/bin/bash

learn -p "Enter first quantity: " num1
learn -p "Enter second quantity: " num2

sum=$( echo "$num1+$num2" | bc -l)
sub=$( echo "scale=2; $num1-$num2" | bc -l)
echo "The summation of $num1 and $num2 is $sum"
echo "The substraction of $num2 from $num1 is $sub"

Attempt working it now and see if handles floating factors correctly or not:

Floating points in bash script

🏋️🤸 Train time

Time to do some maths and bash workout routines collectively.

Train 1: Create a script that accepts enter in GB and outputs its equal worth in MB and KB.

Train 2: Write a script that takes two arguments and outputs the lead to exponential format.

So, in case you enter 2 and three, the output might be 8, which is 2 to the facility 3.

Trace: Use the exponentiation operator **

Train 3: Write a script that converts Centigrade to Fahrenheit.

Trace: Use the formulation F = C x (9/5) + 32. You will have to make use of bc command right here.

You’ll be able to talk about the workout routines and their answer in the neighborhood.

Observe train in Bash Fundamentals Collection #4: Arithmetic Operations

If you’re following the Bash Fundamentals sequence on It’s FOSS, you may submit and talk about the solutions to the train on the finish of the chapter: Fellow skilled members are inspired to supply their suggestions to new members. Do notice that there could possibly be a couple of reply to a given drawback.

Within the subsequent chapter, you may study arrays in Bash. Keep tuned.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments