Linux Shell script strategy (1.5), linuxshell
1.5 use shell for mathematical operations
In any programming language, arithmetic operations are essential, and shell is no exception.
1.5.1 Use let, (), and [] for arithmetic operations
- You can use the normal variable value assignment method to define a value.String. We can use let, (), [], and other operators to perform arithmetic operations on these variables. For example:
#! /Bin/bashno1 = 4 # Here, the no1 string is stored in the form of no2 = 5 # Here, the no2 string is stored in the form of let result = no1 + no2 echo $ result # The output result is 9let no1 ++ # equivalent to let no1 = no1 + 1 echo $ no1 # The output result is 5let no2 -- # equivalent to let no2 = no2-1echo $ no2 # The output result is 4let no1 + = 5 # equivalent let no1 = no1 + 5 echo $ no1 # The output result is 10let no1-= 5 # equivalent to let no1 = no1-5echo $ no1 # The output result is 5 no1 = 4 # Here the no1 literal string format storage no2 = 5 # Here, the result is stored in the form of a no2 string = $[no1 + no2] echo $ result # The output result is 9 result = $ [$ no1 + 5] # In ubuntu cannot run normally, no1 not foundecho $ result # The output result is 9 result = $(no1 + 50) # The $ before the brackets cannot be lost. Otherwise, an error is returned. echo $ result # The output result is 54.
1.5.2 use expr for arithmetic operations
- Expr is a more advanced operator than the preceding three operators, so you can watch for advanced operations. For example:
#! /Bin/bashresult = 'expr 3 + 4' # It is not a single quotation mark, echo $ result # The output result is 7 result = 'expr 3 + 4' # echo $ result every space between 3 and + # The output result is 3. + 4
- Note: Methods in 1.5.1 and 1.5.2 can only calculate integers, but cannot calculate floating point numbers.
1.5.3 perform arithmetic operations using bc
- Bc is an advanced tool for mathematical operations. This precision calculator contains a large number of options. parameters are usually placed before the specific operation to be executed, and the semicolon is used as the delimiter, pass bc through sdtin. For example:
Echo "4*0.56" | bc # output result is 2.24no = 54 result = 'echo "$ no * 1.5" | bc 'echo $ result # output result is 81.0 echo "scale = 2; 3/8 "# The output result is 0.37no = 100 echo" obase = 2; $ no "Based on the scale decimal precision. | bc # converts the target to binary, the default Operating System is 10 no = 1100100 echo "obase = 10; ibase = 2; $ no" | bc # obase = 10, ibase = 2 echo "sqrt (100) "| bc # Calculate the square root echo" 10 ^ 10 "| bc # Calculate the square
-Note: The obase is the target base, and the ibase is the original base. By default, the original base is 10.
1.5.4 reference
Introduction to Linux Shell scripts