In bash, Bash's math is a little awkward, it's hard to adapt and remember, so you have to write a blog post to make it easier to look through. There are four ways to perform mathematical operations:
A, let order
Copy Code code as follows:
#/bin/bash
Num1=13
Num2=14
Let sum= $num 1+ $num 2
Echo $sum
#自增
Let sum++
#自减
Let sum--
#简写形式
Let Sum+=1
Let sum-=2
#顺便吐槽下, let sum= (1+3) * (2+2) Incredibly not, really rotten there!
II, $[] form
Copy Code code as follows:
#!/bin/bash
sum = $[99+88]
#[] also uses variables
num1=11
Num2=22
sum=$[$num 1+ $num 2]
Three, $ (()) way
Copy Code code as follows:
#!/bin/bash
sum=$ ((1+2))
# $ (()) can be used () for priority operation arrangement
Sum=$ (((1+2) *3))
Echo $sum #9
Iv. You can also use the expr command, which requires an operand and an operation symbol to be empty
Copy Code code as follows:
#!/bin/bash
Expr 3 + 4 #7
sum= ' expr ' #33后有空格, "+" after a space, if the writing is sum= ' expr 3+4 ', echo $sum will be 33+44
Echo $sum #77
The above 4 kinds of methods do not support floating-point operations, to carry out floating-point operations, you should use the BC command, syntax format is relatively simple:
Copy Code code as follows:
#!/bin/bash
Sum= ' echo 222.222+333.333 | BC '
Echo $sum
#sum = ' echo 12.228222+ (22222*2) | BC ' incredibly not, decisively despise it.