Shell programming-conditional judgment (2)
The condition of Shell programming determines the conditional test operation test command to test whether a specific expression is valid. When the condition is true, the return value of the test statement is 0, otherwise it is other numerical format 1:test conditional expression format 2: [conditional expression]
File testing
[operator file or directory]
Commonly used test operators
-d: test whether it is a directory
-e: test whether a directory or file exists
-f: test whether it is a file
-r: test whether the current user has permission to read
-w: test whether the current user has permission to write
-x: test whether the current user has permission to execute
Integer value comparison
[integer 1 operator integer 2]
Commonly used test 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
String comparison
Format 1: [string 1 = string 2]
[string 1! = string 2]
Format 2: [- z string]
Logic test
Format 1: [expression 1] operator [expression 2].
Format 2: command 1 operator command 2.
Commonly used test operators
-an or &: logic and the meaning of "and"
-o or | |: logical OR, meaning "or"
!: logical No
Structure of If statement single branch structure if / / conditional test operation then / / command sequence fi / / end command sequence judgment
Script example: #! / bin/bash# compare input integers large or small read-p "Please enter an integer:" numif [$num-ge 5] then echo "this large" fi
Double branch structure if / / conditional test operation then / / command sequence 1 else / / command sequence 2fi / / end command sequence judgment
Script example: #! / bin/bash# compare input integers large or small read-p "Please enter an integer:" numif [$num-ge 5] then echo "this big" else echo this small "fi"
Multi-branch structure if / / conditional test operation 1 then / / Command sequence 1elif / / conditional test operation 2 then / / Command sequence 2else / / Command sequence 3fi / / end command sequence judgment
#! / bin/bashread-p "Please enter your score:" numif [$num-gt 85] & & [$num-le 100] then echo "excellent" elif [$num-gt 60] & & [$num-le 85] then echo "good" else echo "failed" fi
Nested if sentence #! / bin/bashread-p "Please enter your match time:" numif [$num-lt 10] then echo "Congratulations on entering the final" read-p "your gender is:" sex if [$sex = "male"] then echo "you enter the men's group" else echo "you enter the women's group" fielse echo "Sorry you missed the final" fi
Thank you for reading!