Use of if in shell, shellif use
Compare if in shell
Shell determines whether an array contains an element:
Ary = (1 2 3)
A = 2
If [["$ {ary [@]}" = ~ "$ A"]; then
Echo "a in ary"
Else
Echo "a not in ary"
Fi
The method to compare the two strings is as follows:
If ["$ test" x = "test" x]; then
The key points here are:
1. Use a single equal sign
2 Note that there is a space on both sides of the equal sign: This is a unix shell requirement.
3. Note that the last x of "$ test" x is specially arranged, because when $ test is null, the above expression becomes x = testx, obviously, they are not equal. Without this x, the expression returns the error [: =: unary operator expected
Binary comparison operator, which compares variables or numbers. Note the difference between numbers and strings.
Integer comparison
-Eq equals to, for example, if ["$ a"-eq "$ B"]
-Ne is not equal to, for example, if ["$ a"-ne "$ B"]
-Gt is greater than, for example, if ["$ a"-gt "$ B"]
-Ge is greater than or equal to, for example, if ["$ a"-ge "$ B"]
-Lt is less than, for example, if ["$ a"-lt "$ B"]
-Le is less than or equal to, for example, if ["$ a"-le "$ B"]
Greater than (double parentheses required), such as: ("$ a"> "$ B "))
> = Equal to or greater than (double parentheses required), for example: ("$ a"> = "$ B "))
AWK can be used for small data comparison
String comparison
= Equals, for example, if ["$ a" = "$ B"]
= Equal to, such as: if ["$ a" = "$ B"], equivalent to =
Note: The = function has different behaviors in [[] and [], as shown below:
1 [[$ a = z *] # true if $ a starts with "z" (pattern matching)
2 [[$ a = "z *"] # If $ a is equal to z * (character matching), the result is true.
3
4 [$ a = z *] # File globbing and word splitting will occur
5 ["$ a" = "z *"] # If $ a is equal to z * (character matching), the result is true.
For a bit of explanation, File globbing is a stenographer of files, for example, "*. c" is, and then ~ Yes.
But file globbing is not a strict regular expression, although the structure is similar in most cases.
! = Not equal to, such as: if ["$ "! = "$ B"]
This operator uses pattern matching in the [[] structure.
Greater than, in the ASCII alphabetic order. For example:
If [["$ a"> "$ B"]
If ["$ a" \> "$ B"]
Note: ">" needs to be escaped in the [] structure.
For more information, see Example 26-11.
-Z string is "null". The length is 0.
-N string is not "null"
Note:
To use-n in the [] structure, you must use "" To cause variables. Use a string that is not! -Z or a string that is not referenced by "", put it in the [] structure. In general
Work, but this is not safe. It is a good habit to use "" To test strings.
If simplified
If [condition judgment 1] & (|) [condition Judgment 2]; then
Elif [condition judgment 3] & (|) [condition judgment 4]; then
Else
Execute the third content program
Fi