Bash (Scripting) - Subtraction

by
Jeremy Canfield |
Updated: March 23 2022
| Bash (Scripting) articles
Here is a basic example of how to subtract whole numbers in a Bash Shell script.
#!/bin/bash
echo $((2 - 1))
Which should return the following.
1
Or like this.
#!/bin/bash
sum=$((2 - 1))
echo $sum
Or like this.
#!/bin/bash
x=2
y=1
sum=$((x - y))
echo $sum
decimal
The following can be used when dealing with non-whole numbers (decimals), piping to the bc command.
#!/bin/bash
x="2.47"
y="1.178"
sum=$(echo "$x - $y" | bc)
echo $sum
Or using the awk command.
#!/bin/bash
x="2.47"
y="1.178"
sum=$(awk "BEGIN{print $x - $y}")
echo $sum
Did you find this article helpful?
If so, consider buying me a coffee over at