1.5 using the shell for mathematical operations
In any programming language, arithmetic operations are essential, and the shell is no exception.
1.5.1 arithmetic operations using Let, (()), and []
- You can use the normal variable assignment method to define a value, which is that it is saved as a string . We can make these variables perform arithmetic operations by using the Let, (()), [] and other operators. For example:
#!/bin/bashno1=4 #此处no1义字符串形式存储No2=5 #此处no2义字符串形式存储 LetResult=no1+no2Echo $result #输出结果为 9 Letno1++#等价于 let No1=no1+1Echo $no 1 #输出结果为5 Letno2--#等价于 let no2=no2-1Echo $no 2 #输出结果为 4 Letno1+=5 #等价于 let No1=no1+5Echo $no 1 #输出结果为10 Letno1-=5 #等价于 let No1=no1-5Echo $no 1 #输出结果为 5no1=4 #此处no1义字符串形式存储No2=5 #此处no2义字符串形式存储result=$[No1 + NO2]Echo $result #输出结果为9result=$[$no 1+5]#ubuntu中不能正常运行, No1 not foundEcho $result #输出结果为9result=$ ((No1 + -))#括号前的 $ must not be lost, otherwise errorEcho $result #输出结果为
1.5.2 using expr for arithmetic operations
- Expr is a more advanced operator than the above three operators and can alert you to advanced actions. For example:
#!/bin/bash34` #此处用的不是单引号,而是tab键上面那个键的符号echo$result #输出结果为7 3+4` #3与+号之间每空格echo$result #输出结果为 3+4
- Note: Methods in both 1.5.1 and 1.5.2 can only be evaluated on integers and cannot be calculated with floating-point numbers.
1.5.3 using BC for arithmetic operations
- BC is a high-level tool for mathematical operations, this precision calculator contains a number of options, the parameters are usually placed before the specific operation to be performed, and a semicolon as a delimiter, passed through Sdtin BC. For example:
Echo "4 * 0.56"| Bc#输出结果为2.no= WuResult= 'Echo "$no * 1.5"| BC 'Echo $result#输出结果为81.0Echo "SCALE=2;3/8"#通过scale舌质小数的精度, the output is 0.37no= -Echo "obase=2; $no"| Bc#进制转换, the target binary is binary, and the default original system is tenno=1100100Echo "obase=10;ibase=2; $no"| Bc#obase =10,ibase=2Echo "sqrt (+)"| Bc#计算平方根Echo "10^10"| Bc#计算平方
-Note: The Obase is the target system, the IBase is the original, and the original is 10 by default.
1.5.4 Reference
Linux Shell Script Raiders
Linux Shell Script Raiders (1.5)