標籤:
可以利用 let
、(())
、[]
進行基本的算術操作,進階操作使用bc
更加高效。
直接看代碼把,輸出很清楚。
let
[zhengweiwu 22:17 ~]$ no1=4[zhengweiwu 22:24 ~]$ no2=5[zhengweiwu 22:24 ~]$ let result=no1+no2[zhengweiwu 22:24 ~]$ echo $result9[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 $result9
[]
[zhengweiwu 22:26 ~]$ result=$[no1+no2][zhengweiwu 22:27 ~]$ echo $result9[zhengweiwu 22:27 ~]$ result=$[no1+no2+1][zhengweiwu 22:27 ~]$ echo $result10
(())
[zhengweiwu 22:28 ~]$ result=$((1+1))[zhengweiwu 22:28 ~]$ echo $result2[zhengweiwu 22:28 ~]$ result=$(( 10 +1))[zhengweiwu 22:29 ~]$ echo $result11
bc
[zhengweiwu 22:29 ~]$ echo "4*3.5" | bc14.0[zhengweiwu 22:29 ~]$ echo "4*3.54" | bc14.16[zhengweiwu 22:30 ~]$ result=$(echo "$no1*0.44" | bc) # 作為子shell計算結果[zhengweiwu 22:30 ~]$ echo $result1.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)" | bc10[zhengweiwu 22:35 ~]$ echo "10^10" | bc10000000000
使用shell進行數學運算