Shell programming often involves the calculation of numerical values, and sometimes it is easy to forget or confuse the scenarios for these calculation commands, which is a summary of commonly used calculations. The main include let, BC, expr, (()) and so on.
1. Let
using the format: let expression, the expression must be a complete expression, that is, both sides of the equal sign. Can only be assigned, does not support floating-point arithmetic, direct output is not supported
$ var=$ let var+ =2 #var =, Middle cannot have spaces $ let var=var+2 # Var=$ let var*=2 #var = $letvar/=2 # var=14
Unable to calculate floating point number, error
$ var=2.5$ let var+ =1-bash:let:2.5: syntax error: Invalid arithmetic operator (error symbol is ". 5")
2. BC
Commonly used, support floating-point arithmetic
Echo " up"| BC #2Echo "1.5+1.5"| BC #3.0Echo "3-1.2"| BC #1.8Echo "1.5*1.5"| BC #2.2Echo "10/3"| BC #3Echo "SCALE=2;10/3"| BC #3.33
Do you see a difference in the accuracy of multipliers and divisor? Set other parameters under test
Echo "1.5*1.33333"| BC #1.99999Echo "1.5111111111111111111111*1.33333"| BC #2.0148097777777777777777Echo "4/5"| BC #0Echo " the"| BC #0Echo "6/5"| BC #1
The accuracy of the multiplication output is consistent with the longest progress of the phase multiplier. Integer division results are rounded. Of course, it can be assigned a value
var=$ (echo"|bc") #var =2
3. Expr
floating-point arithmetic is not supported, note the numbers and spaces in the calculation characters
Expr 1+1#2Expr 1-1#0Expr 1\*1#1Notethe number is preceded by a \, otherwise errorExpr 1/1#1Expr 1+1 #1 +1, inconsistent with expectationsExpr 1.0+1 #输出语法错误var=$(Expr 1+1) #var =2var2=$(Expr${var} +2) #var2 =4
4, $ (())
Floating-point arithmetic is not supported, the window is not supported to execute $ (()) directly,
var=$ (()) #1 whether there are spaces in the middle of the +1 operator without affecting the calculation
v1=10
V2=15
var=$ ((V1+V2))
var=$ (($v 1+ $v 2))
a=$ ((1 + 1.0)) #提示语法错误
It can be found that the variable with no $ value symbol in $ (()) does not affect the calculation.
5. Awk
Awk combined with the use of print can be a good variety of complete numerical calculations, including floating point number and precision control.
awk ' begin{printf 1.0/2.0} ' #0.5 awk'begin{printf ' 5.2f% ", 10/3}' #3.$ var1=Ten $ var2=3awk'begin{printf "%5.2f\n", v1/v2} ' #3.33
Finally, let's look at an example, output the value of
#!/bin/Bashi=1MAX=5 while [${i}-lt ${max}]; Do "${i}\n" I =$ (($i + 1)) done
Output results
1 2 3 4
[Shell programming] Examples of numerical calculation methods in shell programming