可以利用 let、(())、[]进行基本的算术操作,高级操作使用bc更加高效。
直接看代码把,输出很清楚。
let
[linux 22:17 ~]$ no1=4
[linux 22:24 ~]$ no2=5
[linux 22:24 ~]$ let result=no1+no2
[linux 22:24 ~]$ echo $result
9
[linux 22:24 ~]$ let result=result + 0.9 # 运算符两侧不能有空格
-bash: let: +: syntax error: operand expected (error token is "+")
[linux 22:25 ~]$ let result=result+0.9 # 只能进行整数运算
-bash: let: result=result+0.9: syntax error: invalid arithmetic operator (error token is ".9")
[linux 22:25 ~]$ echo $result
9
[]
[linux 22:26 ~]$ result=$[no1+no2]
[linux 22:27 ~]$ echo $result
9
[linux 22:27 ~]$ result=$[no1+no2+1]
[linux 22:27 ~]$ echo $result
10
(())
[linux 22:28 ~]$ result=$((1+1))
[linux 22:28 ~]$ echo $result
2
[linux 22:28 ~]$ result=$(( 10 +1))
[linux 22:29 ~]$ echo $result
11
bc
[linux 22:29 ~]$ echo "4*3.5" | bc
14.0
[linux 22:29 ~]$ echo "4*3.54" | bc
14.16
[linux 22:30 ~]$ result=$(echo "$no1*0.44" | bc) # 作为子shell计算结果
[linux 22:30 ~]$ echo $result
1.76[linux 22:30 ~]$ echo "scale=2;3/8" | bc # 设定小数精度
.37
[linux 22:31 ~]$ echo "scale=4;3/8" | bc
.3750
[linux 22:31 ~]$ echo "scale=6;3/8" | bc
.375000[linux 22:31 ~]$ no=100
[linux 22:33 ~]$ echo "obase=2;$no" | bc # 输出为2进制,默认输入进制为10进制
1100100
[linux 22:33 ~]$ no=1100100
[linux 22:33 ~]$ echo "obase=10;ibase=2;$no" | bc # 指明输出进制和输入进制
100[linux 22:34 ~]$ echo "sqrt(100)" | bc
10
[linux 22:35 ~]$ echo "10^10" | bc
10000000000