The role of various parentheses in the shell (), (()), [], [[]], {}

Source: Internet
Author: User
Tags arithmetic

One, parenthesis, round brackets () 1, single parenthesis () ① command group. The commands in parentheses will be executed in a new sub-shell sequence, so the variables in parentheses cannot be used by the rest of the script.   Multiple commands in parentheses are separated by semicolons, and the last command can have no semicolon, and there is no space between the commands and the parentheses. The ② command is replaced. Equivalent to ' cmd ', the shell scans the command line once, discovers the $ (CMD) structure, executes the cmd in $ (cmd) once, obtains its standard output, and then places the output in the original command.    Some shells are not supported, such as TCSH. The ③ is used to initialize the array. such as: Array= (a b c d) 2, double parenthesis (()) ① integer extension. This extended calculation is an integer-type calculation and does not support floating-point types. (exp) structure expands and computes the value of an arithmetic expression, if the result of the expression is 0, the exit status code returned is 1, or false, and a non-0-valued expression returns an exit status code of 0, or "true". If the logical judgment, the expression exp is true is 1, false is 0.② as long as the operators and expressions in parentheses conform to the C-language arithmetic rules, they can be used in $ (exp) or even in the trinocular operator. For different carry (such as binary, octal, hex) operations, the output is automatically converted to decimal. such as: Echo $ ((16#5f)) result is 95 (16 decimal) ③ simple (()) can also redefine the value of variables, such as a=5; ((a++)) You can redefine $a as 6④ is commonly used for arithmetic operations comparisons, and the variables in the double brackets can not use the $ symbol prefix. Multiple expressions are supported in parentheses, separated by commas.  as long as the expression in parentheses conforms to the C-language rules, For example, you can use for ((i=0;i<5;i++)) directly. If you do not use double brackets, then for i in ' seq 0 4 ' or for I in {0..4}. If you can use the IF (($i <5) directly, if you do not use double brackets, then if [$i-lt 5].
Two, brackets, square brackets []  1, single brackets []   ①bash internal command, [and test is equivalent. If we don't specify the absolute path, we usually use Bash's own commands. The left bracket in the if/test structure is the command ID that calls test, and the right bracket is judged by the close condition. This command takes its arguments as a comparison expression or as a file test, and returns an exit status code based on the results of the comparison. The if/test structure does not have to be in the right bracket, but this is required in the new bash. The comparison operators available in    ②test and [] are only = = and! =, both are used for string comparisons and are not available for integer comparisons, and integer comparisons can only be used in the form of-EQ,-GT. The greater than sign is not supported either for string comparisons or for integer comparisons. If you really want to use, you can use the escape form for string comparisons, if you compare "AB" and "BC": [AB \< BC], the result is true, that is, the return status is 0. Logic and logic in [] or using-A and-o are represented.    ③ character Range. Used as part of a regular expression to describe a matching range of characters. The regular is not used within brackets as a test purpose.    ④ in the context of an array structure, brackets are used to refer to the number of each element in the array. &NBSP;&NBSP;&NBSP;2, double brackets [[]]    ①[[is a keyword in the Bash programming language. is not a command, [[]] structure is more general than [] structure. There is no filename extension or word splitting between all characters in [[and]], but parameter extensions and command substitution occur.    ② supports pattern matching of strings, and even supports shell regular expressions when using the =~ operator. String comparisons can be made to the right as a pattern, not just a string, such as [[Hello = = Hell]], the result is true. Matches a string or wildcard character in [[]] without the need for quotation marks.    ③ use [[...]] The conditional judgment structure, rather than [...], can prevent many logic errors in the script. For example,,&&, | |, <, and > operators can normally exist in the [[]] conditional judgment structure, but if they appear in the [] structure, an error will be found.For example, you can directly use if [[$a! = 1 && $a! = 2]], if you do not apply double brackets, if [$a-ne 1] && [$a! = 2] or if [$a-ne 1-a $a! = 2]. ④bash the expression in double brackets as a separate element and returns an exit status code.
Example:
[CPP]View PlainCopy 
  1. if ($i <5)
  2. If [$i-lt 5]
  3. If [$a-ne 1-a $a! = 2]
  4. If [$a-ne 1] && [$a! = 2]
  5. if [[$a! = 1 && $a! = 2]]
  6. For I in $ (SEQ 0 4); Do echo $i;d One
  7. For i in ' seq 0 4 '; Do echo $i;d One
  8. For ((i=0;i<5;i++)); Do echo $i;d One
  9. For i in {0..4}; Do echo $i;d One
Three, curly braces, curly braces {}1, general usage ① brace extension. (wildcard (globbing)) expands the file name in curly braces. In curly braces, white space is not allowed, unless the whitespace is referenced or escaped. First: Expand the comma-delimited list of files in curly braces. such as touch {a,b}.txt result is a.txt b.txt. The second type: in curly braces with dots (.. The sequential file list of the splits expands, for example: touch {A. D}.txt results for a.txt b.txt c.txt d.txt [CPP]View PlainCopy 
    1. # ls {ex1,ex2}.sh     
    2. ex1.sh  ex2.sh    
    3. #&NBSP;LS&NBSP;{EX{1..3},EX4}.SH&NBSP;&NBSP;&NBSP;&NBSP;
    4. ex1.sh   ex2.sh  ex3.sh  ex4.sh    
    5. #&NBSP;LS&NBSP;{EX[1-3],EX4}.SH&NBSP;&NBSP;&NBSP;&NBSP;
    6. ex1.sh  ex2.sh   ex3.sh  ex4.sh    
The ② code block, also known as an internal group, actually creates an anonymous function. Unlike the commands in parentheses, the commands in curly braces do not run with a new child shell, meaning that the remainder of the script can still be used in parentheses. The commands in parentheses are separated by semicolons, and the last one must have semicolons.    There must be a space between the first command and the opening parenthesis of the {}. 2, several special replacement structures ${var:-string},${var:+string},${var:=string},${var:?string}①${var:-string} and ${var:=string}: If the variable var is empty, Replace the ${var:-string} with string in the command line, or the variable var is not empty, replace ${var:-string} with the value of the variable var; substitution rules for ${var:=string} and ${var:-string} Is the same, the difference is ${var:=string} if Var is empty, replace ${var:=string} with string and assign string to var: ${var:=string} A common use is to determine whether a variable is assigned a value, If not, assign a default value to it.
The substitution rule for ②${var:+string} is the opposite of the above, that is, when Var is not empty, it is replaced with a string, and if Var is empty, it is not replaced or substituted for the variable var value, that is, the null value. (because the variable var is empty at this time, the two statements are equivalent)
The ③${var:?string} substitution rule is: if the var variable is not empty, replace ${var:?string} with the value of the variable Var, and if the variable var is null, the string is output to the standard error and exited from the script. We can use this attribute to check if the value of the variable is set.
Supplemental extensions: In the above five alternative structures, the string is not necessarily a constant value, the value of another variable or the output of a command can be used. 3. Four Pattern matching replacement structure

Pattern Matching Memory Method:
# is to get rid of the left side (on the keyboard # on the left side)
% is removed to the right (on the keyboard% on the right of $)
The single symbol in #和% is the minimum match, and the two same symbol is the maximum match.

${var%pattern},${var%%pattern},${var#pattern},${var# #pattern} First mode: ${variable%pattern}, when this mode, the shell looks in the variable , see if it gives the pattern the end of the patterns, and if so, remove the contents of the variable from the command line to the shortest matching pattern on the right.
Second mode: ${variable%%pattern}, in this mode, the shell looks in the variable to see if it is a given pattern end, if so, remove the contents of the variable from the command line to the longest matching pattern on the right
Third mode: ${variable#pattern} In this mode, the shell looks in the variable to see if it starts with a given pattern, and if so, removes the shortest matching pattern from the command line to the left of the variable
Fourth mode: ${variable# #pattern} In this mode, the shell looks in the variable to see if it is a given pattern end, and if so, removes the variable from the command line with the longest matching pattern on the right.
None of these four modes will change the value of variable, where only the * match symbol is used in pattern,% and percent, #和 # #才有区别. The pattern in the structure supports wildcards, * denotes 0 or more arbitrary characters,? indicates that matches only one arbitrary character, [...] Matches the characters inside the brackets, [!...] Indicates a mismatch between the characters in the brackets.
[CPP]View PlainCopy 
  1. # Var=testcase
  2. # echo $var
  3. TestCase
  4. # echo ${var%s*e}
  5. Testca
  6. # echo $var
  7. TestCase
  8. # echo ${var%%s*e}
  9. Te
  10. # echo ${var#?e}
  11. Stcase
  12. # echo ${var##?e}
  13. Stcase
  14. # echo ${var##*e}
  15. # echo ${var##*s}
  16. E
  17. # echo ${var# #test}
  18. Case

4. String extraction and substitution ${var:num},${var:num1:num2},${var/pattern/pattern},${var//pattern/pattern}The first mode: ${var:num}, when this mode, the shell extracts all characters from the first num characters to the end in Var. If NUM is positive, start at the left 0, and if NUM is negative, extract the string from the right, but you must use a space after the colon or a number or the entire num with parentheses, such as ${var:-2}, ${var:1-3}, or ${var: (-2)}.
The second mode: ${VAR:NUM1:NUM2},NUM1 is the position, num2 is the length. Represents starting from the $NUM1 position of the $var string to extract a substring of length $num2. cannot be a negative number.
A third mode: ${var/pattern/pattern} means replacing the first matching pattern of the Var string with another pattern. .
The fourth mode: ${var//pattern/pattern} indicates that all matching patterns in the Var string are replaced with another pattern. [HTML]View PlainCopy
  1. [Email protected] ~]# Var=/home/centos
  2. [Email protected] ~]# echo $var
  3. /home/centos
  4. [[email protected] ~]# echo ${var:5}
  5. /centos
  6. [[email protected] ~]# echo ${var:-6}
  7. Centos
  8. [[email protected] ~]# echo ${var: (-6)}
  9. Centos
  10. [[email protected] ~]# echo ${var:1:4}
  11. Home
  12. [[email protected] ~]# echo ${var/o/h}
  13. /hhme/centos
  14. [[email protected] ~]# echo ${var//o/h}
  15. /hhme/cenths

Iv. parentheses after the symbol $

(1) The value of ${a} variable A, which can be omitted without causing ambiguity.

(2) $ (cmd) command substitution, and the ' cmd ' effect is the same, the result is shell command cmd's output, and some shell versions do not support the form of a $ () command substitution, such as tcsh.

(3) $ (expression) and ' exprexpression ' have the same effect, calculating the numeric value of the mathematical expression exp, where exp can be computed as long as it conforms to the rules of the C language, even the three-mesh operator and the logical expression.

V. Use of

1. more than one command execution

(1) Single parenthesis,(CMD1;CMD2;CMD3) Open a new sub-shell Order execution command cmd1,cmd2,cmd3, each command separated by semicolons, the last command can be no semicolon.

(2) Canda brackets,{cmd1;cmd2;cmd3;} executes the command cmd1,cmd2,cmd3 in the current shell order, separated by semicolons, and the last command must have a semicolon, separated by a space between the first command and the opening parenthesis.
for {} and (), the redirection in parentheses affects only that command, and the redirection outside the brackets affects all the commands in parentheses.

The role of various parentheses in the shell (), (()), [], [[]], {}

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.