This article mainly introduces the Linux Shell Script series (v): Mathematical operations, this article explains the use of Let, (()) and [] arithmetic, using expr for arithmetic operations, using BC for arithmetic operations three ways, the need for friends can refer to the
Arithmetic operations are essential in any programming language, and the shell is no exception.
First, use Let, (()) and [] for arithmetic operations
You can use the normal variable assignment method to define a numeric value, which is that it will be saved as a string. We can use Let, (()), [] and other operators to make these variables to perform arithmetic operations. For example:
The code is as follows:
#!/bin/bash
No1 = 4 ා where No1 meaning string is stored
No2 = 5 ා where NO2 meaning string is stored
Let Result=no1+no2
Echo $result ා output 9
Let-no1 + + (equivalent to let No1 = No1 + 1)
Echo $No 1 output is 5
Let-no2 -- equivalent to let NO2 = No2-1
Echo $No 2 ා output 4
Let-no1 + = 5 ා equivalent to let No1 = No1 + 5
Echo $No 1 output is 10
Let-no1 - = 5 ා equivalent to let No1 = no1-5
Echo $No 1 output is 5
No1 = 4 ා where No1 meaning string is stored
No2 = 5 ා where NO2 meaning string is stored
result=$[No1 + NO2]
Echo $result ා output is 9
Result = $[$No 1 + 5]; No 1 not found
Echo $result ා output is 9
Result = $((No1 +) $is not to be lost, otherwise the error
Echo $result ා output is 54
Third, using expr for arithmetic operations
The code is as follows:
Expr is a more advanced operator than the above three operators, and can alert advanced operations. For example:
/bin/bash!
Result = 'expr 3 + 4' ා not single quotation mark here, but the tab key above the symbol
Echo $result ා output is 7
Result = 'expr 3 + 4' × 3 and + number per space
Echo $result ා output is 3 + 4
Note: The methods in 1.5.1 and 1.5.2 can only be evaluated for integers and cannot be counted in floating-point numbers.
Third, the use of BC for arithmetic operations
BC is an advanced tool for mathematical operations, which contains a large number of options that are usually placed before the specific operation to be performed, with semicolons as delimiters, passing a BC through Sdtin. For example:
Echo "4 * 0.56" | BC ා output 2 24
The code is as follows:
No=54
Result= ' echo ' $no * 1.5 | BC '
Echo $result ා output is 81.0
Echo "scale = 2; 3 / 8", the output is 0.37
No=100
Echo "obase = 2 $no" | BC conversion, the target is binary, the default original 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: Obase is the target, IBase is the original, by default the original system is 10.