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

Source: Internet
Author: User
Tags arithmetic echo command

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

Original: http://www.jb51.net/article/60326.htm

http://blog.csdn.net/good_habits/article/details/27708745.

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

What I want to say here is a few shell parentheses, braces and parentheses, the use of commands, as follows:

1.${var}
2.$ (CMD)
3. () and {}
4.${var:-string},${var:+string},${var:=string},${var:?string}
5.$ ((exp))
6.$ (Var%pattern), $ (Var%%pattern), $ (Var#pattern), $ (var# #pattern)

It is now divided into the following:


The prototype of the variable in 1.Shell: ${var}
Common variable forms are $var, such as

$ var=test
$ echo $var
Test

But when you want to display the variable value plus random characters (I use AA here), it goes wrong, as follows:

$ echo $varAA

$

This should be the original of the variable: ${var}, that is, a curly brace to limit the scope of the variable name, as follows
$ echo ${VAR}AA
Testaa
$

With this feature, we can easily write a batch to rename the program, I named it mymv, the program is as follows:
#!/bin/bash

Tail=$1
for filename in ' ls '
Do
MV $filename ${filename}. $tail
Done

The program needs to provide a suffix name, such as C, to replace the C program file with the suffix C, see the following test:
$ ls
A b C
$ MYMV C
$ ls
A.C B.C C.C
$

It seems that the program is running very well, but this is not a perfect program, there are 2 issues to note:
A, there is no subdirectory under the directory, if there is a directory, assuming that dir, it will also be changed to DIR.C, which is obviously not what we want, it should be fixed to the program to identify the directory.
B, it is not helpful to process the parameters of the program, the program should be friendly enough, when the user does not have a given suffix name should be able to handle, like the above will directly to the file added a point (.), which is obviously not what we want.

Because our purpose is to illustrate ${var}, this is enough, so there is no further modification to the above program.

2. Command replacement $ (cmd)
command to replace $ (cmd) and sign ' cmd ' (note that this is not a single quote, on an American keyboard, ' is the key below ESC ') has the same
$ ls
A b C
$ echo $ (LS)
A b C
$ Echo ' ls '
A b C

Let's analyze the command echo $ (LS) in order to understand what the so-called command substitution means:
The shell scans the command line again, finds the $ (CMD) structure, executes the cmd in $ (cmd) once, obtains its standard output, and then places the output in the original command, the $ (LS) position in echo $ (LS), which is the replacement of the $ (LS) and then the Echo command.
As follows:
echo $ (LS) is replaced with Echo a b C
Note here that the error output of the command in $ (CMD) is not replaced, only the standard output is replaced:
$ var=$ (cat D) # # #文件d在当前目录不存在
CAT:D: No file or directory
$ echo $var

$ # # #显然var变量的值是空的

3, a string of command execution () and {}
() and {} are executed on a string of commands, but differ:
A, () just re-open a sub-shell for a sequence of commands to execute
b,{} Executes a string of commands in the current shell
C, () and {} All put a string of commands inside the parentheses, and the commands are separated by a number;
D, () The last command can be used without a semicolon
e,{} The last command to use a semicolon
f,{} must have a space between the first command and the opening parenthesis
G, each command in () does not have to have spaces in parentheses
H, () and the redirection of a command inside the {} brackets only affects the command, but redirects outside the brackets affect all the commands in the parentheses

Let's look at a few examples:
$ var=test
$ (var=notest; Echo $var) # # #变量var值为notest, which is valid in a child shell
Notest
$ echo $var # # #父shell中值仍为test
Test
$ {var=notest; echo $var;} # # #注意左括号和var之间要有一个空格
Notest
$ echo $var # # #父shell中的var变量的值变为了notest
Notest
$ {Var1=test1;var2=test2;echo $var 1>a;echo $var 2;} # # #输出test1被重定向到文件a中,
Test2 # # #而test2输出则仍输出到标准输出中.
$ Cat A
Test1
$ {Var1=test1;var2=test2;echo $var 1;echo $var 2;} >a # # #括号内命令的标准输出全部被重定向到文件a中
$ Cat A
Test1
Test2

Here is an example of a footstep:

(
echo "1"
echo "2"
) | awk ' {print nr,$0} '

4, several special replacement structures: ${var:-string},${var:+string},${var:=string},${var:?string}
A,${var:-string} and ${var:=string}
If the variable var is empty, replace ${var:-string} with string in the command line, or the variable var is not empty, then replace ${var:-string} with the value of Var.
Such as:
$ echo $newvar

$ echo ${newvar:-a}
A
$ echo $newvar # # #变量newvar的值仍然是空, but the previous command line ${newvar:-a} was replaced with a

$ newvar=b
$ echo ${newvar:-a} # # #变量newvar的值不为空时, ${newvar:-b} In this command line is replaced with $newvar, b
B
$

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, Assign a string to the variable var:


$ echo $newvar

$ echo ${newvar:=a}
A
$ echo $newvar # # #变量newvar被赋值为a, while ${newvar:=a} is replaced by a
A
$ echo ${newvar:=b} # # #变量newvar不为空 (whose value has been assigned to a), then ${newvar:=b} is replaced with the value of Newvar (that is, b)
A
$ echo $newvar
A

A common use of ${var:=string} is to determine whether a variable is assigned a value, or assign it a default value if not.
If you set the default editor:
PHP Code:
echo You use editor: ${editor:=/bin/vi}

B,${var:+string}
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)
$ echo $newvar
A
$ echo ${newvar:+b}
B
$ echo $newvar
A
$ newvar=
$ echo ${newvar:+b}

$

C,${var:?string}
The substitution rule is: If the variable var is not empty, then replace ${var:?string} with the value of the variable Var, and if the variable var is empty, 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.
$ newvar=
$ echo ${newvar:? No value set for Newvar}
Bash:newvar: The value of Newvar is not set
$ newvar=a
$ echo ${newvar:? No value set for Newvar}
A
$

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.
$ echo ${var:-' date '}
Day March 6 02:10:39 CST 2005
$ echo ${var:-$ (date)}
Day March 6 02:11:46 CST 2005
$ a=test
$ echo ${var:-$a}
Test
$

Extended calculation of 5.POSIX Standard: $ ((exp))
This calculation is an operator that conforms to the C language, meaning that any operator that conforms to C can be used in $ (exp) or even a trinocular operator.
Note: This extended calculation is an integer-type calculation and does not support floating-point types. If the logical judgment, the expression exp is true is 1, false is 0.
$ echo $ ((3+2))
5
$ echo $ ((3>2))
1
$ echo $ ((25<3? 2:3))
3
$ echo $var

$ echo $ ((var=2+3))
5
$ echo $var
5
$ echo $ ((var++))
5
$ echo $var
6
$

Well, the above example is enough, which also shows that this extended operation is very powerful.

6. Four pattern matching replacement structure: ${var%pattern},${var%%pattern},${var#pattern},${var# #pattern}
The meanings of these four structures are: ${var%pattern} and ${var%%pattern} that match from the rightmost (that is, the end), ${var#pattern} and ${var# #pattern} from the leftmost (that is, the beginning). Where ${var%pattern} and ${var#pattern} are the shortest matches, ${var%%pattern} and ${var# #pattern} are the longest matches. Only wildcard characters are used in pattern to have the longest and shortest match, otherwise there is no maximum minimum match.

The pattern in the structure supports wildcards, * denotes 0 or more arbitrary characters, which represent 0 or one arbitrary character, [...] Matches the characters inside the brackets, [!...] Indicates a mismatch between the characters in the brackets.
$ VAR=AABBBCCBBDBB
$ echo ${var%b}
Aabbbccbbdb
$ echo ${var%%b}
Aabbbccbbdb
$ echo ${var#a}
Abbbccbbdbb
$ echo ${var# #a}
Abbbccbbdbb
$ echo ${var%*b}
Aabbbccbbdb
$ echo ${var%%*b}

$ echo ${var#a*}
Abbbccbbdbb
$ echo ${var# #a *}

$

The above is a simple example of the use of four pattern matching replacement structures.

Other (see Parameter Expansion in Man bash)

${parameter/pattern/string}
Pattern substitution. The pattern is expanded to produce a pat‐
Tern just as in pathname expansion. Parameter is expanded and
The longest match of pattern against its value was replaced with
String. If pattern begins with/, all matches of pattern is
Replaced with string. Normally only match is
Replaced. If pattern begins with #, it must match at the Begin‐
Ning of the expanded value of parameter. If pattern begins with
%, it must match at the end of the expanded value of parameter.
If string is null, matches of the pattern is deleted and the/fol‐
lowing pattern may omitted. If parameter is @ or *, the sub‐
Stitution operation is applied to each positional parameter in
Turn, and the expansion is the resultant list. If parameter is
An array variable subscripted with @ or *, the substitution
Operation is applied through member of the array in turn, and
The expansion is the resultant list.

(()): A pair of parentheses is used in two places.

1,for Cycle,

for (EXPR1; expr2; expr3)

Here is a pair of parentheses inside the expression, GNU's document states that EXPR1 support Shell arithmetic;expr2 is not 0 o'clock, EXPR3 is assigned and the statement executes. That's a lot of trouble, and it takes time to figure out what a shell arithmetic is. In fact word, support the digital conditions. Like what:

for (a=0; a<10; a++); do echo $a; Done

Output 0 1 2 3 (with line wrapping Oh ~ ~ ~)

2, Mathematical expression

(()) and $ (())

The usage of (()) is the same as let, so there is no need to explain it more.

$ (()) is the result of the calculation, can be used in double quotes inside, such as:

echo "1+2=$ ((1 + 2))"

Will output 1+2=3

(): one round Bracket

In the For loop, the same as C syntax.

Or a subroutine that returns the return value of the entire expression inside. The variables inside are local, and the changes are not taken outside. Example Child

A=1

(a=3; Echo $a)

echo A

The result is 3 1

There is also a circle array ... This one doesn't mean anything to God.

[]: A square bracket, is a bash command, the Man manual can be found, like test, in the manual can see a lot of usage. For example-b-c-gt-eq a lot of what, also useful as-a expression with,-o expression or so

[[]]: a square bracket is an enhanced version of the shell, it is a reserved word, inside support | | && wait for these symbols. Generally, I like to use this.

There's a relatively complex {}

Several useful, differentiated variables, such as:

VAR=ABCD; Echo ${VAR}EFG;

This way, bash doesn't think the variable is VAREFG.

There are also used to intercept the string ${} syntax is more flexible, there is no long explanation, we are interested to search their own information, general my script to use the string processing, this can be done.

code block. Used to differentiate the code, but there is a difference between (), is to add at the end;

1. ()

Running in a child shell
(a=1); Echo $a, the result is empty, because A=1 is not running in the current shell (a=1);(echo $a) is also empty. Not in the same child shell
The assignment of the array, see the last supplement

2. (())

Expression evaluation
A=1; ((a++)); Echo $a, when a is 2.

3.< () and > ()

Process, you can read the execution result of the command as a file
such as Comm before the general need to sort, then you can comm < (sort 1.lst) < (sort 2.lst)
or paste < (cut-t2 file1) < (cut-t1 file1)
, similar to pipelines, but supports multiple inputs.

4.$ ()

$ (CMD) to execute the result of CMD, such as CMD is echo ls, then execute LS, such as file$ (which bash), which bash result is/bin/bash, so file $ (which bash) equals file/bin/ Bash. If you are $ (LS) and your current directory has only a B two files, then execute a B, then the system will prompt, the command is not found.

5.$ (())

Expression extension, and (()) very similar, but this is a little different, $ (()) cannot be directly $ ((b++)), B=1;echo $ ((++b)) at this time B equals 2, the display is also 2,b=1;echo $ ((b++)) then B equals 2, the display is 1.

6.[] and [[]]

[] is test,[] and [[]] are conditional expressions, but [[]] have a higher tolerance than [], if A is empty, then [$a-eq 0] will be an error, but [[$a-eq 0]] does not, so generally will use [[]] or ["$a"-eq 0],[[]] supported work can also be more than [], such as [[AAA =~a{3}]],
[] There is another use, if you have a1-a9 nine files in the current directory, you can use a[1-9] to replace these nine files. A little attention, you can't use a[1-20] to replace A1-A20, you have to A[1-9] a1[0-9] A20.

7.$[]

The past form of $ (()) is now not recommended for use

8.{}

{1..30} is 1-30, or/{,s}bin/means/bin/and/sbin/,ab{c,d,e} represent ABC, ABD, Abe

9.${}

Variable, a lot of usage, you can view man bash.
Write these first, and then think about adding them later.

Add: () also is the assignment of the array, such as A= (1 3 5), then ${a[0]}=1;${a[1]}=3;${a[2]}=5, it should be noted that the subscript is starting from 0

The parentheses in the shell have their special usage and are summarized as follows:

1. Parentheses after the symbol $

${a} The value of variable A to omit curly braces without causing ambiguity.
The $ (cmd) command is replaced with the result of the shell command cmd output, and the ' cmd ' effect is the same, although some shell versions do not support the $ () Form of command substitution, such as tcsh.
$ (exp) and ' expr exp ' 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.

2. More than one command execution

(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.
{cmd1;cmd2;cmd3;} In the current shell Order execution command CMD1,CMD2,CMD3, the commands are separated by semicolons, the last command must have a semicolon, the first command and the opening parenthesis must be separated by a space.
for {} and (), the redirection in parentheses affects only that command, and the redirection outside the brackets affects all the commands in parentheses.

3. Special use of double brackets

(()) enhanced use of parentheses, often used in arithmetic operations comparisons. The variables in the double brackets can not use the $ symbol prefix, as long as the expressions in parentheses conform to the C-language operation rules, and multiple expressions are supported by commas.
For example, you can directly use for ((i=0;i<5;i++)), 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].
[[]] enhanced square bracket usage, often used for string comparisons. Mainly used for conditional testing, expressions in double brackets can use &&, | |, <, > C language Syntax.
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] .

(go) 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.