I. Arithmetic of integers
(1) Use Let expression, no need to add ' $ ' before variable
Let sum=num1+num2
(2) $[ expression ], before the variable can be added $, or not add $
SUM=$[NUM1 + num2] sum2=$[$num 1-5] Sum3=$[num1 + 3]
(3) $ ( expression ), before the variable can be added $, or not add $
result=$ (($num 1 + num2-5))
(4) expr, using the ' ' character to widen the expression, or using the $ (expr expression), the operand and operator must be separated by a space
result= ' expr $num \* 4 ' #乘法 * need to escape result2=$ (expr $num/3)
Ii. arithmetic of floating-point numbers
BC is a high-level tool for mathematical operations, using semicolons as delimiters, passed to BC via stdin.
(1) Set decimal precision
Specify the number of decimal digits for the result by setting the value of the scale
$ echo "SCALE=2;4/3" | BC $1.33
(2) Binary conversion
Converts the input number to the obase of the value set by setting the value of obase
$ echo "Obase=2;3" | bc #转换为二进制 $ 11 $ echo "Obase=8;3" | bc #转换为八进制 $ 3 $ echo "obase=8;9" | bc #转换为八进制 $ 11 $ echo "Obase =16;10 " | bc #转换为十六进制 $ a
(3) Some advanced applications
$ echo "sqrt (16)" | BC $4 $ echo "10 ^ 2" | BC $100
Iii. examples
#!/bin/bash num1=3 num2=5 #使用let时, no need to add $ before variable let sum=num1+num2 echo "$num 1 + $num 2 = $sum let num1++ #自增 let num2-- #自减 echo "num1= $num 1, num2= $num 2" let num1+=5 #复合运算 let num2-=2 echo "num1= $num 1, num2= $num 2" #使用 $[expression] for calculation div=$[num1 / num2] echo "$num 1 / $num 2 = $div" sss=$[num1 + num2] echo "$num 1 + $num 2 = $sss" num3=$[num1 - 3] echo "num3=$ Num3 " #使用 $ ((expression)), where the variable in the expression can be used in $ or without $ num4=$ (($num 1 + num2 - num3 + 4)) echo " num4= $num 4 " #使用 expr calculation, operands and operators must be separated by spaces num5= ' expr $num 1 + $num 3 ' echo "num5= $num 5" num6= ' expr $num $num 4 ' echo "num6= $num 6" # Since the operand and operator are not separated, it becomes a string and does not calculate result= ' expr $num 1 \* 4 ' #乘法 * need to escape echo ' result= $result ' result2=$ (expr $num 2 / 3) echo "result2= $result 2" #以上都只能进行整数的计算, floating-point numbers cannot be manipulated
Results:
3 + 5 = 8
num1=4, num2=4
num1=9, num2=2
  9/2 = 4
9 + 2 = one
& Nbsp; num3=6
num4=9
num5=15
num6=2+9 # This is the result of an operand and an operator that are not separated by
result=36
result2=0
This article is from the "Snow Dancer" blog, please be sure to keep this source http://happytree007.blog.51cto.com/6335296/1712338
Li UX Shell arithmetic