使用shell进行数学运算

可以利用 let(())[]进行基本的算术操作,高级操作使用bc更加高效。

直接看代码把,输出很清楚。

let

[zhengweiwu 22:17 ~]$ no1=4
[zhengweiwu 22:24 ~]$ no2=5
[zhengweiwu 22:24 ~]$ let result=no1+no2
[zhengweiwu 22:24 ~]$ echo $result
9
[zhengweiwu 22:24 ~]$ let result=result + 0.9 # 运算符两侧不能有空格
-bash: let: +: syntax error: operand expected (error token is "+")
[zhengweiwu 22:25 ~]$ let result=result+0.9 # 只能进行整数运算
-bash: let: result=result+0.9: syntax error: invalid arithmetic operator (error token is ".9")
[zhengweiwu 22:25 ~]$ echo $result
9

[]

[zhengweiwu 22:26 ~]$ result=$[no1+no2]
[zhengweiwu 22:27 ~]$ echo $result
9
[zhengweiwu 22:27 ~]$ result=$[no1+no2+1]
[zhengweiwu 22:27 ~]$ echo $result
10

(())

[zhengweiwu 22:28 ~]$ result=$((1+1))
[zhengweiwu 22:28 ~]$ echo $result
2
[zhengweiwu 22:28 ~]$ result=$(( 10 +1))
[zhengweiwu 22:29 ~]$ echo $result
11

bc

[zhengweiwu 22:29 ~]$ echo "4*3.5" | bc
14.0
[zhengweiwu 22:29 ~]$ echo "4*3.54" | bc
14.16
[zhengweiwu 22:30 ~]$ result=$(echo "$no1*0.44" | bc)  # 作为子shell计算结果
[zhengweiwu 22:30 ~]$ echo $result
1.76
[zhengweiwu 22:30 ~]$ echo "scale=2;3/8" | bc # 设定小数精度
.37
[zhengweiwu 22:31 ~]$ echo "scale=4;3/8" | bc
.3750
[zhengweiwu 22:31 ~]$ echo "scale=6;3/8" | bc
.375000
[zhengweiwu 22:31 ~]$ no=100
[zhengweiwu 22:33 ~]$ echo "obase=2;$no" | bc # 输出为2进制,默认输入进制为10进制
1100100
[zhengweiwu 22:33 ~]$ no=1100100
[zhengweiwu 22:33 ~]$ echo "obase=10;ibase=2;$no" | bc # 指明输出进制和输入进制
100
[zhengweiwu 22:34 ~]$ echo "sqrt(100)" | bc
10
[zhengweiwu 22:35 ~]$ echo "10^10" | bc
10000000000

你可能感兴趣的:(使用shell进行数学运算)