Conditional testing and comparison of shell scripts

Conditional testing and comparison of shell scripts

Shell consolidates and reviews a series of notes, sets up a Flag, and updates Shell application scenarios that may be encountered in related work from time to time.

1. Conditional Test of Shell Script

Various tests are performed in various conditional structures and flow control structures of bash, and then different operations are performed according to the test results, sometimes combined with conditional statements such as if to complete test judgments to reduce program running errors.

After executing the conditional test expression, it usually returns "true" or "false", just as the return value after executing the command is 0 for true and non-zero for false.

Common syntax for conditional testing

Conditional test syntax Description
Syntax 1: test <test expression> Use the test command to perform conditional test expressions, with at least one space between test and expression
Syntax 2: [<test expression>] The method of conditional test expressions through [] (single brackets) is the same as the test command, with at least one space between the boundary and the expression
Syntax 3: [[ <test expression> ]] Use [[]] (double brackets) for conditional test expressions, with at least one space between the boundary and the expression
Syntax 4: ((<test expression>)) The method of conditional test expressions through (()) (double parentheses), generally used in if statements, (()) and expressions do not need to leave spaces

Description:

  • The test command in Syntax 1 is equivalent to [] in Syntax 2, [[]] is an extended test command, (()) is often used in arithmetic operations
  • [[]] (double brackets) can use wildcards for pattern matching, which is different from other syntax patterns
  • &&, ||, , >, <Other operators may be used [[]] in, but not to [], typically used in [] -a, -o, -gt(整数), -lt(整数)and other command line parameters instead of the operator
  • For integer relational operations, you can also use Shell's arithmetic operators (())

1.1 test condition test

testEquivalently [], the three basic functions are to judge files, strings, and integers. Support using to 与或非connect expressions

only test available comparison operators ==and !=, both for string comparisons, for comparison is not an integer, an integer comparison only use -eq, -gtsuch parameters form, as required 大于>or 小于<compare string, must be added Escape symbols such as[ ab \< bc ]

[root@aurora study]# test -f test.txt && echo true || echo false
true

If the test.txtfile exists, the output is true, otherwise output false, -f to determine whether a regular file

test -z “tuzaza” && echo 1 || echo 0

If the length of the test string is 0, output 1; otherwise, output 0 to -zdetermine whether the length of the string is 0

Tips : More knowledge about test test expressions can be performed to man testview the help

1.2 [] (brackets) conditional test

 [ -f /home/study/test.txt ] && echo 1 || echo 0

If the /home/study/test.txtfile exists, output 1, otherwise outputs 0

1.3 [[]] (double brackets) conditional test

[[]]Pattern matching string support, using =, ~like Shell operator supports regular expressions, the logical combination can not use the test -oand -a, but the use of &&and||

When comparing strings, treat the right side as a pattern (the string is not double-quoted, and the double-quoted string is considered a text string), if [[ hello==hell? ]]true

[[ -f /home/study/test.txt ]] && echo 1 || echo 0

If the /home/study/test.txtfile exists, output 1, otherwise output 0

1.4 (()) (double parentheses) conditional test

(())Equivalent to let, can only perform assignment operations on integers

(())The value of arithmetic expression does not $need to be added in front of if and while judgments, but needs to be added to the echo output value $, such asecho $(( c = a+b+1 ))

When using let or (()) assignment, you can also use expr+backticks instead

let a = $b + $c 等价于 a = `expr $b + $c`
a=1; let “a<0”; echo $?
a=1; ((a<0)); echo $?

if((a>0));then
echo x greater
else;
echo x not greater
fi

2. File test expression

Commonly used file test operators

Common file test operators Description
-b file, b is spelled as block The file exists and is a block (device) file is true
-c file, c is spelled as char The file exists and is a character (device) file is true
-d file, d is spelled as directory The file exists and is a directory file is true
-f file, f is all spelled as file The file exists and is a normal file is true
-e file, e is all spelled exist File exists is true
-r file, r is all spelled read The file exists and is readable as true
-s file, s is all spelled as size The file exists and its length is greater than 0 is true
-S, file, S spelled as Socket The file exists and is a network socket is true
-s file, s is spelled as size The file exists and the size is not 0 is true
-w file, w spelled out as write The file exists and can be written as true
-x file, x is all executable File exists and executable is true
-p file, p is all spelled as pipe File exists and is a command pipeline is true
-L file, L is spelled as link The file exists and is a link file is true
f1 -ef f2, ef all spelled as equal file The files f1 and f2 have the same index number (you can judge whether the same file is the same, hard link)
f1 -nt f2, nt all spelled as newer than If the file f1 is newer than the file f2, it is true, calculated according to the modification time of the file
f1 -ot f2, ot is all spelled older than If the file f1 is older than the file f2, it is true, calculated according to the modification time of the file

More about the file test operator can be man testviewed

2.1 Special condition test expression case

Example 1. Test expression format without if

When condition 1 is established, command 1, command 2, and command 3 are executed at the same time. The format of the test expression without if is as follows:

[ 条件1 ] && {
    
    
命令1
命令2
命令3
}
[[ 条件1 ]] && {
    
    
命令1
命令2
命令3
}
上面的判断语句等价于下面if语句的效果。
if [ 条件 ]
then
  命令1
  命令2
  命令3
fi

Example 2. Use the logical operator ||
When the condition is not true, execute multiple commands in braces, use the logical operator ||

[ -f /etc ] || {
    
    
echo 1
echo 2
echo3
}

Tips : If you write the above script on one line, each command in the braces needs to end with a semicolon. As [ -f /etc/services ] && { echo 1; echo 2; echo3; }. Although the two methods in the case are very concise, they are not as easy to understand as the if conditional statement.

3. String test expression

The functions of the string test operator include: comparing whether two strings are the same, whether the length of the test string is 0, and whether the string is NULL, etc.

Note: NULL is to distinguish between zero-length strings and empty strings through bash

String test operator

Commonly used string test operators Description
-n 字符串 If the length of the string is not 0, it is true
-with 字符串 True if the length of the string is 0
"String 1" = "String 2" True if string 1 is equal to string 2
"String 1"! = "String 2" True if string 1 is not equal to string 2

Description:

  • For string testing, be sure to add double quotes before comparing the strings. Such as[ -n “$myvar” ]
  • There must be spaces at both ends of the comparison symbol (for example, =and !=), otherwise the result will be wrong even if no error is reported
  • !=And =can be used for the same two strings

Example-string test operator

[ -n “abc” ] && echo 1 || echo 0
test -n “abc” && echo 1 || echo 0

4. Integer binary comparison operators

Integer binary comparison operator

Use comparison symbols in [] and test Comparison symbols used in (()) and [[]] Description
-eq == or = Equal
-born != Not equal
-gt > Greater than
-give >= Greater equal
-lt < Less than
-the <= Less than equal

Description:

  • =!=也可以在[]中做比较,但在[]中使用包含><的符号时,需要用反斜线协议/
  • 也可以在 [[]] 中使用包含-gt-lt的符号
  • 比较符号两端也要有空格

例子1.二元数字在 [] 中使用 -gt、-le 类符号的比较

[ 2 -gt 1 ] && echo 1 || echo 0
[ 2 -ge 1 ] && echo 1 || echo 0 

例子2.二次元数字配合不同类型发操作符在[[]]中的比较

[[ 65 < 66 ]] && echo 1 || echo 0

例子3.二元数字在 (()) 中的比较

(( 3 > 2 )) && echo 1 || echo 0

5. 逻辑操作符

逻辑操作符

在[]和test中使用的操作符 在[[]]和(()中使用的操作符 说明
-a && And,与,两端为真结果为真
-o || Or,或,两端其一为真,结果为真
! ! Not,非,两端相反,结果为真

例子1.()(单中括号)文件测试

[ -f /etc/host -a -f /etc/services ] && echo 1 || echo 0

例子2.数值比较

[ 5 -eq 6 -o 5 -gt 3 ] && echo 1 || echo 0
((5==6||5>3)) && echo 1 || echo 0

6. 测试表达式test、[]、[[]]、(())的区别

不同符号测试表达式test、 []、[[]]、(())的区别

测试表达式符号 []等价于test [[]] (())等价于let
边界是否需要空格 需要 需要 不需要
逻辑操作符 !、-a、-o !、&&、|| !、&&、||
整数二元比较操作符(关系比较操作符) -eq、-gt、lt、-ge、-le 或 >、< -eq、-gt、lt、-ge、-le或=、>、<,不可以使用>=、<= =、>、<、>=、<=
字符串比较操作符 =、==、!=、-n、-z,>、< 需要被转义 =、==、!=、-n、-z,>、< 不需要被转义 =、==、!=
文件比较操作符 -r、-l、-w、-x、-f、-d、-s、-nt、-ot -r、-l、-w、-x、-f、-d、-s、-nt、-ot 不支持
数学运算符 +、-、*、/、% 不支持 +、-、*、/、%
是否支持通配符匹配 不支持 支持 不支持
组合 用各自逻辑符号连接的数字(运算)测试、文 件测试、字符测试

Guess you like

Origin blog.csdn.net/qq_36148847/article/details/109190326