1. 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"]
- < less (requires double brackets), such as: (("$a" < "$b" )
- <= is less than or equal (requires double brackets), such as: (("$a" <= " $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
2. String comparisons
- = equals, such as:if [ "$a" = "$b"]
- = = equals, such as:if [ "$a" = = " $b"], and = equivalent
Attention:
The way to compare two strings for equality is if ["$test" x = "Test" x]; Then here are the key points: 1 use a single equal sign 2 notice that there is one on each side of the equal sign
Space: This is the UNIX shell requirement 3 Notice that 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
Note: The behavior of the = = function is different in [[]] and [], as follows:
- [[ $a == z* ]] # if $ A Span class= "string" > "Z" begins (pattern match) then true
- [ $ A == "z*" ]] # if $ A equals z* (character match) Then the result is true
- &NBSP;&NBSP;
- [ $a == z* ] # File globbing and word splitting will occur
Li class= "alt" >[ "$a" == "z*" ] # if $ 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.
< less than, in ASCII alphabetical order. such as:
if [["$a" < "$b"]
If ["$a" \< "$b"]
Note: the "<" in the [] structure needs to be escaped.
> 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"
Attention:
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 Script Integer Comparison