Shell if [[]] and [] differences | | &&

Source: Internet
Author: User
Tags arithmetic syslog

    • [] and test

Both are the same, and the test expr and [expr] have the same effect on the command line.

The three basic functions of test are to judge a file, judge a string, and judge an integer. Supports the use of "and or not" to concatenate expressions.

The comparison operators available in Test are only = = and! =, both for string comparisons, not for integer comparisons, and for integer comparisons only with-eq,-gt this form.

Do not use a greater than or less than sign for both string comparisons and integer comparisons. Of course, if you really want to use is also possible, for string comparison can use angle bracket escape form, if compare "AB" and "BC": [AB \< BC], the result is true, that is, the return status of 0.

    • [[ ]]

This is a command built into the shell, which is much more powerful than the test just said. Supports pattern matching for strings (even shell regular expressions are supported when using the =~ operator). Logical combinations can be used without the use of test-a,-o && | |.
String comparisons can be made to the right as a pattern (this is the case with the right string without double quotes.) If the string on the right is double-quoted, it is considered a text string. ), not just a string, such as [[Hello = = Hell]], the result is true.

Note: When using [] and [[]] do not stingy space, each of the two sides have a space, [[1 = 2]] The result is "false", but [[[1==2]] The result is "true"!

    • Let and (())

The two are the same (or basically the same, and the braces are slightly weaker than let). The main arithmetic operations (none of the two above), but also suitable for integer comparison, you can directly use the familiar <,> and other comparison operators. You can directly use variable names such as Var without the need to $var this form. Multiple expressions with semicolon-delimited support

############################################################################################################### #####################

1. First, though very similar, the two are conceptually different levels of things.
"[[" is a keyword, and many shells (such as ash BSH) do not support this approach. Ksh, Bash (reportedly introduced support for [[support] from 2.02 onwards.
"[" is a command that is equivalent to test and is supported by most shells. In most modern SH implementations, "[" and "Test" are internal (builtin) commands, in other words, "test"/"[" is not called when/some/path/to/test such an external command (if there is such a command).


2.[[]] structure is more generic than the bash version of []. All characters between [[and]] are not separated by a file extension or a tag, but there are parameter references and command substitutions.

use [[...]] test structure than with [...] To prevent many logic errors in the script. For example, &&,| |,< and > Operators can be passed in a [[]] test, but errors will occur in the [] structure.

3. (()) structure expands and computes the value of an arithmetic expression. If the expression value is 0, it returns 1 or false as the exit status code. An expression of a value other than 0 returns a 0 or True as an exit status code. This structure is just the opposite of the previous Test command and [] structure.

4.[...] As a shell command, so the expression in it should be its command-line argument, so the string comparison operator ">" and "<" must be escaped, otherwise it becomes an IO redirect operator (see the example above in 2). Do not need to be escaped in [[Medium < and >];
Because "[[" is a keyword, the command line extension is not done, so the relative syntax is slightly stricter. For example
In the [...] You can enclose the operators in quotation marks, because they are removed when you do a command-line extension, and in [[...] It is not allowed to do so.

5.[[...] Perform arithmetic expansion, while [...] Don't do

6.[[... && && ...] and [...-a ...] are not the same, [[]] is a logical short-circuit operation and [] does not have a logical short-circuit

1) test in Ksh
Number operations can use Let, (()), where the variable $ symbol is not required for the operation, the operator is + 、-、 *,/,%, and expr is not recommended
Numbers are compared using (()), whose operators >, >=, <, <=, = =,! =
You can use arithmetic extensions, such as: ((99+1 <= 101))
Comparison of character expressions using [[]], whose operator =,! =,-N,-Z
The test of the file expression uses [[]], its operator-R,-L,-W,-X,-F,-D,-S,-nt,-ot
The test of a logical expression uses [[]], its operator!, &&, | |
Numeric comparisons, character comparisons, logical tests can be combined, such as $ [["a"! = "B" && 4-GT 3]]
Support for wildcard extensions in bash, such as: [[Hest = h?? T]], [hest = H*t]]
When using (()), spaces are not required to separate the values and operators, and [[]] are used to separate the values and operators with a space.

2) bash differs from [[]] in Ksh
You can also use the [[]] symbol in REDHAT9 bash. But it is recommended to use it strictly in accordance with the above principles.
In bash, the comparison of numbers is best used (()), although [[]] is used, but if the operator >, >=, <, <=, = =,! = are used inside, the result is often wrong, but if you use the operator in [] in [[]]-eq,-ne,-l E,-lt,-GT,-ge ", etc., have not yet found fault. So a combination such as $ [["a"! = "B" && 4 > 3]] (see above) is also not available in bash, with a high error rate.
Example: [["a"! = "B" && > 2]] "judgment result is not normal."
such as [2 \< 10], [[2 < 10]] are not used. It is best to use arithmetic extensions ((99+1 = = 100)) instead of [[99+1-eq 100]].


############################################################################################################### #####################

############################################################################################################### #####################

Operator Describe Example
File comparison Operators
-e filename True if filename exists [-e/var/log/syslog]
-D filename True if filename is a directory [-d/tmp/mydir]
-F filename True if filename is a regular file [-f/usr/bin/grep]
-L filename True if filename is a symbolic link [-l/usr/bin/grep]
-R filename True if filename is readable [-r/var/log/syslog]
-W filename True if filename is writable [-w/var/mytmp.txt]
-X filename True if filename is executable [-l/usr/bin/grep]
Filename1-nt filename2 If filename1 is newer than filename2, it is true [/tmp/install/etc/services-nt/etc/services]
Filename1-ot filename2 If filename1 is older than filename2, it is true [/boot/bzimage-ot Arch/i386/boot/bzimage]
String comparison operators (note the use of quotation marks, which is a good way to prevent whitespace from disturbing the code)
-Z String True if string length is zero [-Z "$myvar"]
-N String True if string length is nonzero [-N "$myvar"]
string1 = string2 True if string1 is the same as string2 ["$myvar" = "One of the three"]
String1! = string2 True if string1 is different from string2 ["$myvar"! = "one of the three"]
Arithmetic comparison operators
Num1-eq num2 Equals [3-eq $mynum]
Num1-ne num2 Not equal to [3-ne $mynum]
Num1-lt num2 Less than [3-lt $mynum]
Num1-le num2 Less than or equal to [3-le $mynum]
NUM1-GT num2 Greater than [3-gt $mynum]
Num1-ge num2 Greater than or equal to [3-ge $mynum]

Test command

The test command is used to check if a condition is true, and it can test for 3 aspects of numeric, character, and file, with its tester and corresponding functions as follows.

(1) Numerical test:

-eq is equal to true.

-ne is not equal to true.

-GT is greater than true.

-ge is true if it is greater than or equal.

-lt is less than true.

-le is less than or equal to true.

(2) String test:

= Equals is true.

! = is not equal to true.

-Z String string length pseudo is true.

The-n string string is true if the length is not pseudo.

(3) file test:

-e file name is true if the file exists.

-r file name True if the file exists and is readable.

-W file name True if the file exists and is writable.

-X file name is true if the file exists and is executable.

-S file name True if the file exists and has at least one character.

-d file name if the file exists and is true for the directory.

-F filename is true if the file exists and is a normal file.

-C file name True if the file exists and is a character-type special file.

-B file name True if file exists and is a block special file



Conditional variable substitution:
The Bash shell can make conditional substitutions of variables, replacing only when certain conditions occur, replacing
The condition is placed in {}.
(1) ${value:-word}

When the variable is undefined or the value is empty, the return value is the contents of Word, otherwise the value of the variable is returned.

(2) ${value:=word}

Similar to the former, except that if the variable is undefined or the value is empty, the value returned in Word will be

Word assigns values to value

(3) ${value:?message}

If the variable is assigned a value, replace it normally. Otherwise, send message messages to the standard error output (if

This substitution appears in the shell program, and the program will terminate running)

(4) ${value:+word}

If the variable is assigned a value, the value is replaced with Word, otherwise no substitution is made

(5) ${value:offset}
${value:offset:length}
Extracts a substring from a variable, where offset and length can be arithmetic expressions.

(6) ${#value}

The number of characters in a variable

(7) ${value#pattern}
${value# #pattern}
Remove the part of value that matches the pattern in the condition that the beginning of value matches the pattern
#与 # #的区别在于一个是最短匹配模式, one is the longest matching pattern.

(8) ${value%pattern}

${value%%pattern}
In (7) similar, just from the tail of value in pattern matching,% and percent of the difference between # and # #一样

(9) ${value/pattern/string}

${value//pattern/string}
Replace the contents of the variable with the content of the pattern match with the contents of the string, the difference between//and the

Note: In the above condition variable substitution, except (2), the rest does not affect the value of the variable itself


#!/bin/bash

var1= "1"
Var2= "2"

The following is the operator-A, which is also noted, with a test command, and a semicolon after the IF condition

if test $var 1 = "1"-a $var 2 = "2"; Then
echo "Equal"
Fi

The following is the OR operator-O, with one as true as you can

if test $var 1! = "1"-o $var 2! = "3"; Then
echo "Not Equal"
Fi

The following are non-operators!
The IF condition is true when executed, if used! operator, the original expression must be false

if! Test $var 1! = "1"; Then
echo "Not 1"
Fi


The above three if are true, so three echo will print

In a document to put these operations in a mess, so I experimented with it

------------------------------------------------------------------------------------------------------

Shell string comparison, judging whether it is a number

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"]
< 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"))

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.
< 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 if [[]] and [] difference | | &&

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.