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

Source: Internet
Author: User
Tags arithmetic

One, parenthesis, round brackets () 1, single parenthesis ()
    • The 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.
    • command Replacement . 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.
    • used to initialize an 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 a 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)
    • The values of variables such as a=5 can also be redefined by simply using (()). ((a++)) to redefine $a to 6
    • Commonly used in arithmetic operations comparisons, the variables in the double brackets may not use the $ symbol prefix. Multiple expressions are supported in parentheses, separated by commas. As long as the expression in parentheses conforms to the rules of the C language, for example, you can use the 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, bracket, square brackets [] 1, single brackets []
    • Bash's internal commands, [and test are 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 for string comparisons, not for integer comparisons, and for integer comparisons to use only the-eq,-gt form. 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.
    • The 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.
2. Double brackets [[]]
    • [[is a key word for 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 the shell's 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 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 sees expressions in double brackets as a single element and returns an exit status code.
If ($i<5) If [$i-Lt5 ] If [$a-Ne1 -A $a!= 2 ] If [$a-Ne1] && [$a!= 2 ] If [[$a!= 1 &&$a!= 2 ]] ForIInch$(Seq0 4);DoEcho $i;Done ForIInch ' Seq 0 4 ';do echo $i ; for  ((i =0; I<5; I++)); do echo $i ; for I in {0.4}; do echo $i ;                 
Three, curly braces, curly braces {}1, general usage

(1) Brace expansion. (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

# ls {ex1,ex2}.sh    ex1.  SH  ex2.  Ex1.  SH ex2.  SH ex3.  SH ex4.  Ex1.  SH ex2.  SH ex3.  SH ex4.                  

(2) A block of code, 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, a few special replacement structure
${var:-string} ${var: +string} ${var: =  String}${var:?  String}                 

1, ${var:-string} and ${var:=string}: If the variable var is empty, use string in the command line to replace the ${var:-string}, or the variable var is not empty, then replace it with the value of variable var ${var:-string The substitution rule for ${var:=string} is the same as ${var:-string}, and the difference is ${var:=string} if Var is empty, replace ${var:=string} with string, Assigning a string to a variable var: ${var:=string} A common use is to determine whether a variable is assigned a value or not, and assign a default value to it.

2, ${var:+string} The substitution rule and the opposite, that is, only when Var is not empty time to replace the string, if Var is empty, do not replace or substitute variable var value, that is, null value. (because the variable var is empty at this time, the two statements are equivalent)

3, {var:?string} substitution rule is: If the variable var is not empty, then use the value of variable var to replace ${var:?string}; 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 remove the left (on the keyboard # on the left of the $)% is to remove the right (on the keyboard% on the  right side)   

The single symbol in #和% is the minimum match, and the two same symbol is the maximum match.

${var%pattern}${varpattern${var#pattern}${ var# #pattern}                
    • The first mode: ${variable%pattern}, this mode, the shell in the variable, to see if it is a given pattern end, if so, from the command line to remove the contents of the variable to the right of the shortest matching mode
    • Second mode: ${variable%%pattern}, when this pattern is found, the shell looks in the variable to see if it is a given pattern end, and if so, Remove the contents of the variable from the command line the longest matching pattern on the right
    • the third mode: ${variable#pattern} This mode, the shell looks in the variable, see if it is a given pattern to start, if it is, Remove the contents of the variable from the command line the shortest matching pattern on the left
    • Fourth mode: ${variable# #pattern} In this mode, the shell looks in variable to see if it is a given pattern end, if it is , remove the contents of the variable from the command line to the longest matching pattern
    • in the four modes, the value of variable is not changed, in which 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.
# var=testcase    # echo $var    testcase    # echo ${var%s*e}       case
4. String extraction and substitution
${var : num}${var :num1:num2} ${var/pattern /pattern}${//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.
[[Email protected]~]# Var=/home/Centos[[Email protected]~]#Echo $var/Home/Centos[[Email protected]~]#echo ${Var:5} /Centos[[Email protected]~]#echo ${Var: -6}Centos[[Email protected]~]#echo ${Var:(-6)}Centos[[Email protected]~]#echo ${Var:1:4} Home [[email protected] ~]# echo ${var/o/ h} /hhme/CentOS [[email protected] ~]# echo ${var //o/h} /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.

      Original source: http://blog.csdn.net/taiyang1987912/article/details/39551385

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.