Bootstrap FreeKB - Bash (Scripting) - Addition and Increment (+)
Bash (Scripting) - Addition and Increment (+)

Updated:   |  Bash (Scripting) articles

Here is a basic example of how to add two numbers in a Bash Shell script.

#!/bin/bash
echo $((1 + 1))

 

Which should return the following.

2

 

Or like this.

#!/bin/bash
sum=$((1 + 1))
echo $sum

 

Or like this.

#!/bin/bash
x=1
y=1
sum=$((x + y))
echo $sum

 


Increment

+ can be used to increment a value.

#!/bin/bash
sum=1
sum=$((sum+1))
echo $sum

 

Which should return the following.

2

 


decimal

The following can be used when dealing with non-whole numbers (decimals), piping to the bc command.

#!/bin/bash
x="1.178"
y="2.47"
sum=$(echo "$x + $y" | bc)
echo $sum

 

Or using the awk command.

#!/bin/bash
x="1.178"
y="2.47"
sum=$(awk "BEGIN{print $x + $y}")
echo $sum

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a99d54 in the box below so that we can be sure you are a human.