There are four kinds of arithmetic operations in Linux, namely expr,let,$[],$ (()).
Here are the four ways to use the arithmetic operations, respectively
First, the use of expr
[[email protected] ~]# Expr 1 + 23[[email protected] ~]# expr 1-2-1[[email protected] ~]# expr 8 + 614[[email protected] ~]# expr 8-62[[email protected] ~]# expr 8 \* 648[[email protected] ~]# expr 8/61[[email protected] ~]# a=3[[email PR Otected] ~]# b=4[[email protected] ~]# expr $a + $b 7
The above are examples of expr doing subtraction operations.
When working with expr, if you want to assign the result of the operation to another variable, you should do the following.
[[email protected] ~]# a= ' expr 2 + 3 ' [[email protected] ~]# echo $a 5
Let's take a look at some of the areas where expr is used.
1, when using expr to do operations, arithmetic and operators to be separated by a space, otherwise it will not be calculated
[Email protected] ~]# expr 1+21+2
2, in the multiplication operation, * front to receive \ Escape, because * in the regular expression inside the meaning of the match multiple
[[email protected] ~]# Expr 2 * 3expr:syntax error
Second, let command
[[email protected] ~]# let A=2+3[[email protected] ~]# echo $a 5[[email protected] ~]# let A=2-3[[email protected] ~]# Echo $a -1[[email protected] ~]# let A=2*3[[email protected] ~]# echo $a 6[[email protected] ~]# let A=2/3[[email protected] ~]# echo $a 0[[email protected] ~]# b=4[[email protected] ~]# c=2[[email protected] ~]# let a= $b/$c [[email protected] ~]# Echo $a 2
When using let, it is generally necessary to assign them to a variable to accept the result of the operation.
Let is not the same as expr, there is no need to add a space between the arithmetic and the operator.
Iii. use of $[]
[[email protected] ~]# A=$[2+3][[email protected] ~]# echo $a 5[[email protected] ~]# a=$[2-3][[email protected] ~]# echo $ A-1[[email protected] ~]# a=$[2*3][[email protected] ~]# echo $a 6[[email protected] ~]# a=$[2/3][[email protected] ~]# Ech O $a 0
Use of four, $ (())
[Email protected] ~]# a=$ ((1+3)) [[email protected] ~]# echo $a 4[[email protected] ~]# a=$ ((1-3)) [[email protected] ~]# EC Ho $a -2[[email protected] ~]# a=$ ((1*3)) [[email protected] ~]# echo $a 3[[email protected] ~]# a=$ ((1/3)) [[Email protected] ~]# Echo $a 0
This article is from the "ssspure" blog, make sure to keep this source http://ssspure.blog.51cto.com/8624394/1862362
Shell Scripting Learning Two: arithmetic operations in the shell