The way to compare two strings for equality is:
If ["$test" x = "Test" x]; Then
Here are a few key points:
1 using a single equals sign
2 Note that there is a space on each side of the equal sign: This is the UNIX shell requirement
3 Notice the last X of "$test" X, which is deliberately arranged, because when $test is empty, the expression above becomes x = Testx, which is obviously not equal. Without this x, the expression would be an error: [: =: unary operator expected
Binary comparison operators, comparing variables or comparing numbers. Note the difference between a number and a string.
Integer comparison
-eq equals, such as: if ["$a"-eq "$b"]
-ne not equal to, such as: if ["$a"-ne "$b"]
-GT greater than, such as: if ["$a"-gt "$b"]
-ge greater than equals, such as: if ["$a"-ge "$b"]
-lt less than, such as: if ["$a"-lt "$b"]
-le less than equals, such as: if ["$a"-le "$b"]
Greater than (requires double brackets), such as: (("$a" > "$b")
>= greater than or equal (requires double brackets), such as: (("$a" >= "$b"))
Small data comparisons can be used with awk
string comparison
= equals, such as: if ["$a" = "$b"]
= = equals, such as: if ["$a" = = "$b"], and = equivalent
Note: The behavior of the = = function is different in [[]] and [], as follows:
1 [[$a = = z*]] # if $ A starts with "Z" (pattern match) then true
2 [[$a = = "z*"] # if $ A equals z* (character match) Then the result is true
3
4 [$a = = z*] # File globbing and word splitting will occur
5 ["$a" = = "z*"] # If a $ A equals z* (character match) Then the result is true
A little explanation, about file globbing is a shorthand for the document, such as "*.c" is, again like ~ also.
But file globbing is not a strict regular expression, although in most cases the structure is more like.
! = does not equal, such as: if ["$a"! = "$b"]
This operator will use pattern matching in the [[]] structure.
Greater than, in ASCII alphabetical order. such as:
if [["$a" > "$b"]
If ["$a" \> "$b"]
Note: the ">" in the [] structure needs to be escaped.
Refer to Example 26-11 for an example of this operator application.
The-Z string is "null". The length is 0.
-N string not "null"
Note:
The use of-N in the [] structure must be used to test the variable. Use a string that is not ""! -Z
Or the string itself, which is not referenced by "", is placed in the [] structure. Although it is generally possible to
To work, but it's not safe. It's a good habit to use "" to test strings .
Shell compares two strings for equality