Reprinted from: Linux Shell arithmetic operations
There are four ways in which the Bash Shell's arithmetic operations are:
1: Using expr external program
Addition R= ' Expr 4 + 5 '
Echo $r
Attention! ' 4 ' + ' 5 ' There should be a gap between the three
R= ' Expr 4 * 5 ' #错误
Multiplication r= ' expr 4 \* 5 '
2: Use $ (())
r=$ ((4 + 5))
Echo $r
3: Use $[]
R=$[4 + 5]
Echo $r
Multiplication
R= ' Expr 4 \* 5 '
r=$ ((4 * 5))
r=$[4 * 5]
Echo $r
Division
r= ' Expr 40/5 '
r=$ ((40/5))
r=$[40/5]
Echo $r
Subtraction
r= ' Expr 40-5 '
r=$ ((40-5))
r=$[40-5]
Echo $r
Find remainder
r=$[100% 43]
Echo $r
(e.g. 2 of 3)
r=$ ((2 * * 3))
r=$[2 * * 3]
Echo $r
Note: Expr does not have a
4: Use the Let command
Addition:
n=10
Let N=n+1
echo $n #n =11
Multiplication:
Let m=n*10
Echo $m
Division:
Let R=M/10
Echo $r
To find the remainder:
Let R=m%7
Echo $r
By emerges:
Let R=m**2
Echo $r
Although the bash shell has four arithmetic operations, not each of which is cross-platform, it is recommended that expr be used.
In addition, we often have 1 operations in script, the following four methods are available:
m=$[m + 1]
m= ' expr $m + 1 '
m=$ (($m + 1))
Let M=m+1
Shell arithmetic operations