when using the Shell's logical operator "[]", you must ensure that there is a space between the operator and the arithmetic. Arithmetic can only use: let,expr and other commands to complete. Today's statement of the double-brace "(())" structure is an extension of the arithmetic and assignment operations in the shell.
1. Syntax:
(expression 1, expression 2 ...)
2. Features:
(1) in a double-brace structure, all expressions can be like the C language, such as: a++,b--, and so on.
(2) in a double-brace structure, all variables may not be added: "$" symbol prefixes.
(3) Double brackets can be used for logical operation, arithmetic
(4) Double bracket structure expands the FOR,WHILE,IF condition test operation
(5) Support for multiple expression operations, separated by "," between each expression
3. Usage examples:
3.1 Extension Arithmetic
The code is as follows:
#!/bin/sh
a=1;
b=2;
c=3;
((a=a+1));
echo $a;
a=$ ((a+1,b++,c++));
echo $a, $b, $c
Operation Result:
SH testsh.sh
2
3,3,4
multiple expressions are supported between the two-parenthesis structure, which is then supported by common C-language operators such as subtraction. If the double parenthesis Band: $, the expression value is obtained and assigned to the left variable.
3.2 Extended logical Operations
The code is as follows:
#!/bin/sh
a=1;
b= "AB";
echo $ ((a>1?8:9));
((b!= "a")) && echo "ERR2";
((a<2)) && echo "OK";
Operation Result:
9
ERR2
OK
3.3 Extended Condition test operation (IF)
The code is as follows:
a=1
b=2
if ((a<b)); Then
echo "true";
fi
if ((a>b)); Then
echo "false"
fi
Operation Result:
true
3.4 Extending Flow control statements (logical relationships)
The code is as follows:
#!/bin/sh
num=100;
total=0;
For ((i=0;i<=num;i++));
Do
((total+=i));
Done
echo $total;
total=0;
i=0;
while ((I<=num));
Do
((total+=i,i++));
Done
echo $total;
if ((total>=5050)); Then
echo "OK";
fi
result of Operation:
5050
5050
OK
with the double parenthesis operator: [[]],[],test logical operation, LET,EXPR is not required.]
Write elegant shell script (v)-Shell (()) Double parenthesis operator