Integer Value Operations
Use the expr command: only integer operations can be performed, and the calculation result is returned by default
Format:
expr integer 1 operator integer 2 ...
Integer values can be provided by variables, directly giving the result of the operation
+ addition expr 43 + 21 , expr $X + $Y -subtraction expr 43 - 21 , expr $X - $Y \ * multiplication expr 43 \* 21 , expr $X \* $Y / division expr 43 / 21 , expr $X / $Y % take the remainder expr 43 % 21 , expr $X % $Y
example:
#!/bin/bash #Calculate the sum of any 2 numbers entered by the user from the terminal read -p " Please enter the first number " num1 read -p " Please enter the second number " num2 sum=`expr $num1 + $num2` echo "$num1 + $num2 = $sum"
Use $[] or $(()) expressions
Need to use echo to output the result, the operation type is similar to expr Multiplication * without escape character \ When using a variable, specify the variable name directly without adding the $ sign
How to perform arithmetic operations in the shell :
let Arithmetic expression let C=$A+ $B $[arithmetic expression] C =$[$A+ $B] $((arithmetic expression)) C =$(($A+ $B)) expr Arithmetic operation expression,
there should be spaces between operands and operators in the expression,
and command references should be used C=`expr $A + $B`
simplification of expressions
Increment and decrement of variables
shorthand expression full expression i++ i=i+1 i-- i=i-1 i*=2 i=i*2 i+=2 i=i+2 i-=2 i=i-2 i%=2 i=i%2
Notice:
i++ : Participate in other operations first, then operate
++i: operate first, then participate in other operations
example:
i=1 echo $((++i)) j=1 echo $((j++))
Operations such as increment / decrement of variables
Use the let command
Manipulate variable values, only operate, do not output results
To see the results, use the echo command
let: only do the operation without returning the calculation result, suitable for self-addition and self-subtraction operations
#!/bin/bash i=10 let i-=2 echo $i let i-=2 echo $i echo ------------------- i=10 let i+=2 echo $i let i+=2 echo $i