Brackets
Brackets are divided into single brackets [] and double brackets [[]]. Square brackets are generally used in expression judgment, and parentheses can also be used in expressions, which will be mentioned later.
Single square brackets []
A=5 B=3 [ $A -eq $B ] 判断A是否等于B [ ${A} -eq ${B} ] 作用同上 [ "${A}" -eq "${B}" ] 作用同上
A=ABC [ $A == "ABC" ] 或写成 [ ${A} == "ABC" ] 或写成 [ "${A}" == "ABC" ] [ $A \> "ABC" ]
[ -d ./aaa.sh -a -e ./bbb ] 测试aaa.sh是否为目录并且bbb是否存在,如果都符合则返回真 [ -d ./aaa.sh -o -e ./bbb ] 测试aaa.sh是否为目录并且bbb是否存在,满足一个条件则返回真
We can see some rules for using single square brackets from the above:
There must be a space between the variable and the square bracket
variable There must also be a space between the operator and the operator
Variables can be referenced directly with $, or they can be referenced with ${} and "${}". Although ${} can be used directly, it is recommended to use "${} ", or use $ directly to quote variables
Strings should be enclosed in double quotes
String comparison generally uses == to test whether the strings are the same, and use < or > for size comparison, in a single To compare characters in parentheses for greater than and less than, use transfer > and <. The comparison principle is to compare ASCII.
In addition, you can also use logical operators like -a and -o in single square brackets
Double square brackets [[]]:
A=5 B=3 [[ $A -eq $B ]] 判断A是否等于B [[ ${A} -eq ${B} ]] 作用同上 [[ "${A}" -eq "${B}" ]] 作用同上
A=ABC [[ $A == "ABC" ]] 或写成 [[ ${A} == "ABC" ]] 或写成 [[ "${A}" == "ABC" ]] 或写成 [[ $A == ABC ]] [[ $A > "ABC" ]]
[[ -d ./aaa.sh && -e ./bbb ]] 测试aaa.sh是否为目录并且bbb是否存在,如果都符合则返回真 [[ -d ./aaa.sh || -e ./bbb ]] 测试aaa.sh是否为目录并且bbb是否存在,满足一个条件则返回真
A=ABC [[ $A =~ "A" ]] 做模式匹配,这个表达式为真 或写成 [[ ${A} =~ "A" ]] 或写成 [[ "$[A]" =~ "A" ]] [[ $A = A* ]] 表达式为真 [[ $A = B* ]] 表达式为假
Single brackets
Brackets
[ 表达式1 -a 表达式2 ] 等效于 [[ 表达式1 && 表达式2 ]] 等效于 [ 表达式1 ] && [ 表达式2 ] 等效于 [[ 表达式1 ]] && [[ 表达式2 ]]
[ 表达式1 -o 表达式2 ] 等效于 [[ 表达式1 || 表达式2 ]] 等效于 [ 表达式1 ] || [ 表达式2 ] 等效于 [[ 表达式1 ]] || [[ 表达式2 ]]
Double parentheses
are commonly used in arithmetic operations and also used in for loops
(ls ./;echo "hello";mkdir -p /tmp/ccc)
For statement
1 to 10 Loop execution
echo "当前目录是:$(pwd)" echo "当前目录是:`pwd`"
While statement form
1 to 10 loop
A=$((5+3)) B=$(($A+4))