Functions (), (), [], [], and {} of various parentheses in shell

Source: Internet
Author: User

Functions (), (), [], [], and {} of various parentheses in shell
I. Parentheses ()1. Single parentheses ()

Command Group. The commands in parentheses will open a new sub-shell for sequential execution, so the variables in parentheses cannot be used by the rest of the script. Multiple commands in parentheses are separated by semicolons. The last command can have no semicolons, and there is no space between each command and the parentheses.

Command replacement. Equivalent to 'cmd', shell scans the command line once and finds the $ (cmd) structure. Then, it executes cmd in $ (cmd) once to obtain its standard output, then place the output to the original command. Some shells are not supported, such as tcsh.

Used to initialize an array. For example, array = (a B c d)

 

2. Double parentheses (())

Integer Extension. This type of extended computation is an integer computation and does not support floating point computation. (Exp) structure extension and calculation of the value of an arithmetic expression, if the expression result is 0, then the returned exit status code is 1, or "false ", the exit status code returned by a non-zero expression is 0 or "true ". If the expression exp is true, it is 1, and false is 0.

② As long as the operators and expressions in parentheses comply with the C language operation rules, they can be used in $ (exp), or even the three-object operator. When performing different carry operations (such as binary, octal, and hexadecimal), all output results are automatically converted to decimal. For example, echo $(16 # 5f) returns 95 (hexadecimal to decimal)

③ You can simply use ().Redefinition of variable valuesFor example, a = 5; (a ++) can redefine $ a as 6

④ UsedArithmetic Operation comparison, Variables in double brackets can be prefixed with the $ symbol. Multiple Expressions can be separated by commas. As long as the expressions in parentheses conform to the C algorithm rules, for example, you can directly use for (I = 0; I <5; I ++). If you do not use double parentheses, for I in 'seq 0 4' or for I in {0 .. 4 }. If you can directly use if ($ I <5), if you do not use double parentheses, then if [$ I-lt 5].

 

2. brackets [] 1. Single brackets []

Bash Internal commands, which are equivalent to test. If we do not need to specify the absolute path, we usually use bash commands. The left brackets in the if/test structure are the command IDs that call test, and the right brackets are used to close the condition judgment. This command uses its parameters as a comparison expression or as a file test, and returns an exit status code based on the comparison result. The if/test structure does not require right brackets, but this is required in the new version of Bash.

② The comparison operators available in Test and [] are only = and! =, Both are used for string comparison and cannot be used for integer comparison. Integer comparison can only be in the form of-eq or-gt. Both string comparison and integer comparison do not support numbers greater than or less than numbers. If you really want to use it, you can use escape form for string comparison. If you compare "AB" and "bc": [AB \ <bc], the result is true, that is, the return status is 0. The logic and logic in [] can be expressed by-a and-o.

Character range. Used as part of a regular expression to describe a matched character range. Regular Expressions cannot be used in brackets for test purposes.

④ In the context of an array structure, brackets are usedReference the number of each element in the array.

 

2. Double brackets [[]

[[It is a keyword of bash Programming Language. It is not a command. The [[] structure is more common than the [] structure. All characters between [and] are not subject to file name extension or word segmentation, but parameter extension and command replacement occur.

String Matching is supported., Use = ~ It even supports regular expressions of shell. When comparing strings, you can use the right side as a pattern, not just a string, such as [[hello = hell? ], And the result is true. [[] Matches strings or wildcards without quotation marks.

③ Using the [[...] condition to determine the structure, rather than [...], can prevent many logical errors in the script. For example, the &, |, <, and> operators can normally exist in the [[] condition judgment structure, but if they appear in the [] structure, an error is returned. For example, you can directly use if [[$! = 1 & $! = 2]. if double parentheses are not applicable, the parameter is if [$ a-ne 1] & [$! = 2] Or if [$ a-ne 1-a $! = 2].

④ Bash regards the expression in double brackets as a separate element and returns an exit code.


Example:

if ($i<5) if [ $i -lt 5 ] if [ $a -ne 1 -a $a != 2 ] if [ $a -ne 1] && [ $a != 2 ] if [[ $a != 1 && $a != 2 ]] for i in $(seq 0 4);do echo $i;done for i in `seq 0 4`;do echo $i;done for ((i=0;i<5;i++));do echo $i;done for i in {0..4};do echo $i;done

 

3. Braces and curly braces {} 1. General Usage

Braces extended. (Globbing) will expand the file name in braces. White spaces are not allowed in braces unless the white space is referenced or escaped. First, expand the comma-separated file list in braces. For example, if you set "touch platform A", the result of "bits. txt" is a.txt B .txt. Type 2: Expand the list of ordered files separated by dots (...) in braces. For example, the result of touch a..d;.txt is a.txt B .txt c.txt d.txt.

# ls {ex1,ex2}.sh ex1.sh ex2.sh # ls {ex{1..3},ex4}.sh ex1.sh ex2.sh ex3.sh ex4.sh # ls {ex[1-3],ex4}.sh ex1.sh ex2.sh ex3.sh ex4.sh

Code blockIs also called an internal group. This structure actually creates an anonymous function. Unlike the commands in parentheses, the commands in braces do not start a new sub-shell, that is, the remaining part of the script can still use the variable in parentheses. The commands in parentheses are separated by semicolons. The last one must also contain semicolons. There must be a space between the first command of {} and the left parenthesis.

 

2. Several Special replacement Structures

$ {Var:-string}, $ {var: + string}, $ {var: = string}, $ {var :? String}

① $ {Var:-string} and $ {var: = string}: If the var variable is empty, replace $ {var:-string} with string in the command line }, otherwise, when the variable var is not empty, replace $ {var:-string} with the value of the variable var. For the replacement rules of $ {var: = string} and $ {var: -string} is the same. The difference is that $ {var: = string} If var is empty, use string to replace $ {var: = string, A common use of assigning a string to the variable var :$ {var: = string} is to determine whether a variable is assigned a value. If not, assign a default value to the variable.

② The replacement rule of $ {var: + string} is opposite to the above, that is, it is replaced with string only when var is not empty, if var is null, It is not replaced or replaced with the value of the variable var, that is, the null value. (Because the variable var is empty at this time, the two statements are equivalent)

③ $ {Var :? String} replacement rule: if the variable var is not empty, replace $ {var:? With the value of the variable var :? String}; if the var variable is null, the string is output to the standard error and exits from the script. We can use this feature to check whether the variable value is set.

Supplementary Extension: In the above five replace structures, string is not necessarily a constant value. It can be the value of another variable or the output of a command.

 

3. Four pattern matching replacement Structures

Pattern Matching memory method:
# Remove the left (on the keyboard # on the left of $)
% Is to remove the right side (% on the keyboard to the right of $)
# The single symbol in and % is the minimum match, and the two identical symbols are the maximum match.

$ {Var % pattern}, $ {var % pattern}, $ {var # pattern}, $ {var # pattern}

First mode: $ {variable % pattern}. In this mode, shell searches for the variable mode to check whether it ends with pattern. If yes, remove the content in variable from the command line from the shortest matching mode on the right.

Mode 2: $ {variable % pattern}. In this mode, shell searches for the pattern in variable to check whether it ends with pattern. If yes, remove the content of variable from the command line from the longest matching mode on the right.

In the third mode: $ {variable # pattern}, shell searches for the pattern in variable to see if it starts with pattern. If yes, remove the content in variable from the command line from the shortest matching mode on the left.

In the fourth mode: $ {variable # pattern}, the shell searches for the pattern in variable to see if it ends with pattern. If yes, remove the content of variable from the command line from the longest matching mode on the right.

The value of variable is not changed in the four modes. The difference is between % and %, # And # only when the * matching symbol is used in pattern. The pattern in the structure supports wildcards. * Indicates zero or multiple arbitrary characters ,? It indicates that it only matches any character, and [...] indicates that it matches the characters in brackets, [!...] It indicates that the characters in the brackets are not matched.

# var=testcase # echo $var testcase # echo ${var%s*e} testca # echo $var testcase # echo ${var%%s*e} te # echo ${var#?e} stcase # echo ${var##?e} stcase # echo ${var##*e} # echo ${var##*s} e # echo ${var##test} case

 

4. String extraction and replacement

$ {Var: num}, $ {var: num1: num2}, $ {var/pattern}, $ {var // pattern/pattern}

First mode: $ {var: num}. In this mode, shell extracts all the characters from the num to the end in var. If num is a positive number, it starts from 0 on the left. If num is a negative number, the string is extracted from the right, but it must be enclosed by a space or a number or a whole num with parentheses, for example, $ {var:-2}, $ {var: 1-3}, or $ {var :(-2 )}.

The second mode is $ {var: num1: num2}. num1 indicates the position and num2 indicates the length. Indicates that the substring with the length of $ num2 is extracted from the position $ num1 of the $ var string. Cannot be negative.

Mode 3: $ {var/pattern} indicates replacing the first matched pattern of the var string with another pattern.

Mode 4: $ {var/pattern} replaces all pattern that can be matched in the var string with another pattern.

 

[root@centos ~]# var=/home/centos [root@centos ~]# echo $var /home/centos [root@centos ~]# echo ${var:5} /centos [root@centos ~]# echo ${var: -6} centos [root@centos ~]# echo ${var:(-6)} centos [root@centos ~]# echo ${var:1:4} home [root@centos ~]# echo ${var/o/h} /hhme/centos [root@centos ~]# echo ${var//o/h} /hhme/cenths

 

4. brackets after the symbol $

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

(2) Replace the $ (cmd) Command, which has the same effect as the 'cmd' command. The result is a shell command cmd input. commands in the form of $ () are not supported in some Shell versions, for example, tcsh.

(3) $ (expression) and 'expression' have the same effect. Calculate the number of exp in the mathematical expression, where exp must comply with the c algorithm rules, even the Three-object operator and logical expression can be computed.

 

5. run multiple commands

(1) single parentheses (cmd1; cmd2; cmd3) open a new sub-shell to execute commands cmd1, cmd2, and cmd3 sequentially. Separate commands with semicolons, the last command can be followed by a semicolon.

(2) single braces: {cmd1; cmd2; cmd3;} execute the command cmd1, cmd2, and cmd3 in the Current shell sequence, and separate the commands with semicolons, the last command must be followed by a semicolon. The First Command and the left parenthesis must be separated by spaces.
For {} and (), the redirection character in brackets only affects this command, while the redirection character outside brackets affects all commands in brackets.

Speak

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.