Shell script-conditional statement
Conditional test
1. File testing
2. Integer value comparison
3. String and logic testing
If statement:
Single branch if statement
Double-branched if statement
Multi-branched if statement
1. File testing
File testing refers to judging whether a file or a directory corresponds to a given path name, or whether a file is readable, writable, executable, and so on.
Basic format
Test conditional expression or [conditional expression]
The common operation options for files are as follows:
Option description-d test whether it is a directory (Directory)-e test whether a directory or file exists (Exist)-f test whether it is a file (File)-r test whether the current user has permission to read (Read)-w test whether the current user has permission to write (Write)-x test whether to set executable (Excute) permission
After doing the above, you can use "$?" The return status value of the test command can be obtained to determine whether it is true or not.
Actual operation
Format one
Test-d / etc/sysconfig (test whether the sysconfig directory in / etc exists) echo $? (if the return value is 0, the condition is valid)
Format two
[- d / etc/sysconfig] echo$ (if the condition is not true, the test value will not be 0 (usually 1))
Integer value comparison
Format: [integer 1 operator integer 2]
Common operation options
1.-eq: equal to (Equal) 2,-ne: not equal to (Not Equal) 3,-gt: greater than (Greater Than) 4,-lt: less than (Lesser Than) 5,-le: less than or equal to (Lesser or Equal) 6,-ge: greater or equal (Greater or Equal)
String comparison
Format 1: [string 1 = string 2] [string 1! = string 2] format 2: [- z string]
Common operation options
1. =: the first string is the same as the second string 2,! =: the first string is different from the second string, or "!" Sign reverse 3,-z: check whether the string is empty, and variables that are not defined or assigned null values will be treated as empty strings
Logic test
Format 1: [expression 1] operator [expression 2]. Format 2: command 1 operator command 2.
Common operation options
1.-an or &: logic and, "and" means 2,-o or | |: logic or, "or" means 3! Logical no, which means "no"
If statement
Single branch structure
If conditional Test Action then Command sequence fi
Double branch structure
If conditional Test Action then Command sequence 1then Command sequence 2fi
Multi-branched structure
If conditional Test Action then Command sequence 1elif conditional Test Operation 2then Command sequence 2else Command sequence 3fi