shell基础03 数学运算

       shell中的数学运算有些局限。主要分为了以下几种类型:

1.   方括号-------只支持整数运算

       [Hermioner@localhost Documents]$ var1=$[1+5]

       [Hermioner@localhost Documents]$ echo $var1

       6
      [Hermioner@localhost Documents]$ var2=$[$var1*2]
      [Hermioner@localhost Documents]$ echo $var2
      12
     [Hermioner@localhost Documents]$ var1=100
     [Hermioner@localhost Documents]$ var2=45
     [Hermioner@localhost Documents]$ var3=$[$var1/$var2]
     [Hermioner@localhost Documents]$ echo $var3
     2

2. 浮点解决方案

     直接使用内建的bash计算器,叫做bc。它支持多种类型的计算

      

      浮点计算会设计到精度的问题,可以通过设置变量scale的值,让它满足我们想要的精度。比如scale=4,意思就是小数点后面保留4位输出

      

     bc可以处理别的数据类型,用时参考。

参考文献

Linux命令行与shell脚本编程大全(第3版)[美] 布鲁姆Richard Blum),布雷斯纳汉Christine Bresnahan) 著,门佳武海峰 译

猜你喜欢

转载自www.cnblogs.com/Hermioner/p/9378812.html