Let's start with an example:
x=1+1echo $x
Are you expecting output 2? Let you down. The output result is 1 + 1. Why? This is because the variable type in shell script is "string" by default, so if the variable type is not specified, 1 + 1 is a "string" instead of a "formula ". So how can we get the desired results? There are many methods, but there are two in summary. One is the type of the Life variable. The other is to process a specific computing formula.
1) First, let's look at the first method: declare the type of the variable.
I made the following changes to the above program:
declare -i xx=1+1echo $x
In the above script, I declare X as an integer, and the output result is 2.
Or you can write:
declare -i xdeclare -i yx=1y=2x=$x+$yecho $x
The output result is 3. If the X and Y types are not declared as integer numbers, the output result is 1 + 2.
2)
A) use the let command: (Note that let only supports integer operations)
let 'x=1+1'echo $x
The output result is 2.
B) use $ []
x=1y=2x=$[ x+y]echo $x
Output result: 3
Note the following:
- $ [] Use the expression in brackets as a mathematical operation to calculate the result and then output it.
- It doesn't matter if you do not add $ when accessing the variables in $ [].
- $ [] Supports the same operators as let, but only integer operations.
C) use $ (())
x=1y=2x=$(( x+y))echo $x
The output result is 3.