Arithmetic Operations
If the variable does not exist or has a null value in the arithmetic expression, the value of this variable is 0.
Numbers in different hexadecimal formats use the "base # Number" notation. The base range is 2 ~ 64
Arithmetic extension:
If a variable exists in the expression, you are advised not to add $ before the variable name to avoid syntax errors caused by the absence of the variable.
If there is a remainder in the division operation result, it is left off unconditionally.
Example:
View Code
1 #! /Bin/bash
2 declare-I a I q s = 0
3 a =$ {1:-255}
4 mask = "128 64 32 16 8 4 2 1"
5 Bmap =
6
7 echo "1 binary carry 128 64 32 16 8 4 2 1"
8 for I in $ mask
9 do
10 q = $ (a/I ))
11 s = $ (s + q ))
12 [$ q-gt 0] & Bmap = $ Bmap "_ 1 _" | Bmap = $ Bmap "_ 0 __"
13 a = $ (a-q * I ))
14 done
15
16 echo "$ s: $ Bmap"
Use external program expr:
Benefit: expr originally serves to display the expression value in "standard output. This feature can be used as a tool for arithmetic operations. Moreover, because it is an external program and has no relationship with the shell version, it can be executed on almost all OS platforms. Cross-platform.
When using expr, pay special attention to whether the "expression" contains special characters of bash shell, such as *, |, <,> ,!, &, (,), And so on. If any, escape with \. Otherwise, an error occurs. Second, in an expression, there must be at least one space character to separate the operator from the operand.
Supported types of operations: addition, subtraction,..., comparison style, locate the position of the sub-string, take the sub-string, calculate the string length, and regard the keyword as a general string.
$ [] Is similar to $ ().
Declare:
Changing the attributes of a variable in advance
In formula, there cannot be a space character between the operator and the operand, and it must be closely connected.
Do not use \ escape for special conformances
Can contain other variables. You do not need to add $
Let is similar