Condition test
1. test command
- Test whether the expression is established, if it is established, return 0 (Boolean value), otherwise return other values
- Boolean value is one of true (True) or false (False), the Boolean value in shell programmingEstablished as 0, Does not hold and is expressed asNon-zero
- Format 1 test conditional expression
- Format 2 [Conditional expression] (There must be spaces on both sides of the expression)
2. File testing
Format
[Operator file or directory]
常用的测试操作符:
-d #测试是否为目录(Directory)
-e #测试目录或文件是否存在(Exist)
-f #测试是否为文件/文件是否存在(File)
-r #测试当前用户是否有权限读取(Read)
-w #测试当前用户是否有权限写入(Write)
-x #测试当前用户是否有权限执行(eXcute)
Example:
3. Integer value comparison
Format
[integer 1 operator integer 2]
常用的测试操作符:
-eq #等于(Equal)
-ne #不等于(Not Equal)
-gt #大于(Greater Than)
-lt #小于(Lesser Than)
-le #小于或等于(Lesser or Equal)
-ge #大于或等于(Greater or Equal)
Expansion:
4. String comparison
Format 1
[String 1 = String 2] or [String 1 == String 2]
[String 1 != String 2]
Format 2
[-z String] Check whether the string is empty (Zero), Variables that are not defined or assigned a null value will be treated as empty strings
[-n string] Check whether there is a string
常用的测试操作符:
= #字符串内容相同
!= #字符串的内容不同,!号表示相反的意思
-z #检查字符串内容是否为空
-n #检查字符串是否存在
5. Logic Test
Format 1
[Expression 1] Operator [Expression 2]
Format 2
[Command 1 Operator Command 2]
-a或&& #逻辑与(而且的意思)
-o或|| #逻辑或(或者的意思)
! #逻辑否
Use -a or -o in the same bracket, use && or || between different brackets
Note: If &&, || operators appear in [], an error will be reported, but &&, || can normally exist in the conditional judgment structure of [[]]
Example: