Advanced Bash-scripting Guide (18): [[] and [] some special cases, bashscripting
The example selected in this article is from the book "Advanced Bash-scripting Gudie", translated by Yang chunmin Huang Yi
For example, [1-eq 1] & [-n "'echo true 1> & 2'"] # true. 1> & 2 indicates to output the standard output to file descriptor 2 (standard error output: screen) 3 [2-eq 2] & [-n "'echo true 1> & 2'"] # (not output) 4 5 [1-eq 2-a-n "'echo true 1> & 2'"] # true, this is the result of an error, is there two conditions in the calculation of the single-brace numeric value? 6 7 [[1-eq 2 &-n "'echo true 1> & 2'"] # (not output), where-a or-o is incorrect, obviously & or | be more secure
-A and-o are generally used with [], for example, ["$ exp1"-a "$ exp2"]
& | It is generally used with [[], for example, [[condition1 & condition2]
Example 22 [$ a = z *] # pattern matching: If $ a starts with a, it is true3 [$ a = "z *"] # character matching: if the value of $ a is equal to z *, It is true4 5 [$ a = z *] # file globbing and word splitting. What does it mean? 6 [$ a = "z *"] # character match: true if the value of $ a is equal to z *
The above is a string comparison, except that the = function has different behaviors in [[] and.
Example 3 2 # Only [[] can be used for hexadecimal conversion. Comparison 3 4 decimal = 15 # decimal 5 octial = 017 # octal 6 hex = 0x0f # hexadecimal 7 if ["$ decimal"-eq "$ octal"] 8 then 9 echo "$ decimal equals $ octal" 10 else11 echo "$ decimal is not equal to $ octal" #15 is not equal to 01712 fi
# It cannot be calculated using single brackets! 13 if [["$ decimal"-eq "$ octal"] 14 then15 echo "$ decimal equals $ octal" #15 equals 01716 else17 echo "$ decimal is not equal to $ octal "18 fi # Use double brackets [[] for calculation! 19 if [["$ decimal"-eq "$ hex"] 20 then21 echo "$ decimal equals $ hex" #15 equals 0x0f22 else23 echo "$ decimal is not equal to $ hex "# [[$ hexadecimal] can also be computed.
24 fi