SoFunction
Updated on 2025-03-09

Various ways to perform mathematical operations through shell

In Bash, the mathematical operations of bash are a bit awkward and are difficult to adapt to and remember. I had to write a blog post for easy reading in the future. There are four ways to perform mathematical operations:

1. Let command

Copy the codeThe code is as follows:

#/bin/bash
num1=13
num2=14
let sum=$num1+$num2

echo $sum

#self-increase
let sum++

#Self-decrease
let sum--

#Abbreviation
let sum+=1
let sum-=2

#By the way, let sum=(1+3)*(2+2) doesn't work, it's really bad, is there any!

2. $[] form

Copy the codeThe code is as follows:

#!/bin/bash
sum = $[99+88]

#[] also use variables
num1=11
num2=22
sum=$[$num1+$num2]

3. $(()) method

Copy the codeThe code is as follows:

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

# $(()) can be used to arrange priority operations
sum=$(( (1+2)*3 ))
echo $sum #9

4. You can also use the expr command, which requires operands and operator symbols to be available.

Copy the codeThe code is as follows:

#!/bin/bash
expr 3 + 4 #7

sum=`expr 33 + 44`#33 has spaces, and "+" has spaces. If you write sum=`expr 3+4`, echo $sum will be 33+44
echo $sum #77

The above four methods do not support floating point number operation. If you want to perform floating point number operation, you should use the bc command, and the syntax format is relatively simple:

Copy the codeThe code is as follows:

#!/bin/bash

sum=`echo 222.222+333.333 | bc`
echo $sum

#sum=`echo 12.228222+(22222*2) | bc` doesn't work, so I decisively despise it.