Shell script (conditional Test & IF judgment)-- Theory 2
Shell script Theory part 2-conditional Test & IF judgment condition Test
In the last blog post, we mentioned that there is a $in the predefined variable. Variables are used to determine whether the command was executed successfully. So how do you use it?
At this point, you need a special testing tool, the test command, to test specific conditions and use $? To judge the return value, the command form is as follows:
Test conditional expression
&
[conditional expression] / / more commonly used
Note: brackets "[" and "]" need to be separated by a space from the conditional expression, otherwise an error will occur!
I. document testing
Format:
[operator file or directory]
Common operators:
-d: test whether it is a directory
-e: test whether the file / directory exists
-f: test whether it is a file
-r: test whether the current user has read permissions
-w: test whether the current user has write permission
-x: test whether the current user has execute permissions
How to use it:
Second, integer value test
Format:
[integer 1 Operand integer 2]
Common operators
-eq: equal to
-ne: not equal to
-gt: greater than
-lt: less than
-le: less than or equal to
-ge: greater than or equal to
How to use it:
Third, string testing
Format:
[string 1 operator string 2]
[- z string] / / determine whether the content of the string is empty
Common operators:
=: the string content is the same
! =: the string content is different
How to use it:
IV. Logic testing
Format:
[expression 1] operator [expression 2]
&
Command 1 operator Command 2
Common test characters:
-an or &: logic and the meaning of "and"
-o or | |: logical OR, meaning "or"
! The logic is no, the conclusion is reversed.
How to use it:
IF statement to judge single branch structure
Format:
If conditional test operation
then command sequence
Fi
Structure flow chart:
Double branch structure
Format:
If conditional test operation
then Command sequence 1
else Command sequence 2
Fi
Structure flow chart:
Multi-branch structure
Format:
If conditional Test Action 1
then Command sequence 1
Elif conditional Test Action 2
then Command sequence 2
Else command sequence 3
Fi
Structure flow chart:
Unfinished to be continued ~