#/bin/bash
Before you start the shell script, be sure to add the above sentence at the beginning of the script and write it with your head, without spaces and blank lines ahead of you. This means telling the system which shell to use to execute the script. If there is no such sentence, some unexpected mistakes may occur.
Let's talk about how arithmetic is done in a shell script or on the command line. You may have found that because the variables in the shell are formatted as character types, if you simply let a variable be equal to an expression, then the output of the variable is the same as the expression, not the result of the expression, such as:
~]$ a=1+2 ~]$ Echo $a 1+2
We want to make a=3, but when we use echo to display a variable, we get the string "1+2".
So what do we do when we want the variable A to be equal to 3?
Here are a few ways to do this:
1. Use the command let to get the desired result, in the form of the var= arithmetic expression
~]$ let a=1+2 ~]$ echo $a 3
In addition, simple arithmetic operations include subtraction, multiplication, division, modulo, and power. Of course, let's function is not only these, basically we can think of the expression can use this command to perform operations, such as self-addition, self-subtraction and other operations:
Let b+=2 equates to let B=b+2let b-=2 equals let b=b-2let b*=2 equals let b=b*2let b/=2 equals let B=b/2let b%=2 Equal to let b=b%2
When a variable is combined with two consecutive plus or minus signs, it is self-added, but there are differences, such as:
1) When the variable is in front, the variable a first assigns the value to the variable B, and then adds one:
~]$ a=2 ~]$ let b=a++ ~]$ echo $b 2 ~]$ echo $a 3
2) When the variable is at the back, the variable A is added first, and then the value is assigned to variable B:
~]$ a=2 ~]$ let B=++a ~]$ echo $b 3 ~]$ echo $a 3
Similarly: This is true when the operator is "-".
2.var=$[arithmetic expression], in the form of: Sum=$[c+b] equivalent to $[$C + $B], in parentheses can be a variable can also be directly an expression, such as
~]$ echo $b 3 ~]$ echo $a 3 ~]$ echo $[a+b]6 or ~]$ echo $ ((1+2)) 3
3.var=$ (arithmetic expression), this method is basically the same as the previous method, but note that the parentheses must be two, which is a reference to the command when there is only one parenthesis.
4.expr ARGU1 ARGU2 ARGU3 ARGU1 and ARGU3 must be numeric, ARGU2 is an operator, and each parameter must be separated by a space, otherwise you cannot output normal results, such as:
~]$ expr 1+21+2 ~]$ expr 1 + 23
5.echo "Arithmetic expression" | Bc
This method uses a pipe line to send an arithmetic expression over the BC command
Like what:
~]$ echo "1+2" | Bc3
The arithmetic operation of shell script programming