Basic syntax and common judgment usage of if in shell

Time:2022-1-12

If, for and while are the keywords of almost all programming languages, and are no exception in shell programming. If is the most frequently used. Since there is no concept of object in shell programming, the comparison and judgment of if is mainly based on the values of string and number:

I Basic syntax of if

1. There should be a space between if and [
2. There must also be a space between [] and judgment conditions
3.] and; No spaces between

II Judgment of string

1.if [ str1=str2 ]; Then fi # returns true when two strings are the same
2.if [ str1!=str2 ]; Then fi # returns true when two strings are not equal
3.if [ -n str1 ]; Then fi # returns true when the length of the string is greater than 0 (judge whether the variable has a value)
4.if [ -z str1 ]; Then fi # returns true when the length of the string is 0

III Judgment of numbers

1. INT1 – EQ INT2 #int1 and INT2 are equal
2.int1 – Ne INT2 #int1 unequal INT2
3.int1 – GT INT2 #int1 greater than INT2
4. INT1 – Ge INT2 #int1 ≥ INT2
5.int1 – LT INT2 #int1 less than INT2
6.int1 – Le INT2 #int1 ≤ INT2

IV Judgment on file attributes

1. – R file # user readable as true
2. – W file # user can write true
3. – x file # user executable true
4. If the – f file # file exists and is a regular file, it is true
5. – D file # if it exists, the directory is true
6. – C file # file exists and is a character device file
7. – B file # file exists and is a block device file
8. If the – s file # file size is not 0, it is true. You can judge whether the file is empty
9. – e file # true if the file exists

V Logical judgment

1. – a # and
2. -o # or
3.! # wrong