How various parentheses are used in the shell _linux shell

Source: Internet
Author: User
Tags arithmetic echo command numeric value

What I want to say here is the parentheses in several shells, the braces and the bracketed variables, and the use of the command, 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 as follows:


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 variable values plus random characters (I'm here with AA), there will be an error, as follows:

$ echo $varAA

$

You should use the prototype of the variable: ${var}, that is, a brace to qualify the range of variable names, as follows
$ echo ${VAR}AA
Testaa
$

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

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

The program needs to provide a suffix name, such as C, which represents the C program file with the suffix C, and look at 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 procedure, there are 2 issues to be noted:
A, there is no subdirectory under the directory, if there is a directory, the assumption is dir, it will also be changed to DIR.C, which is obviously not what we want, should be modified this program can identify the directory.
B, does not help 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 add a point to the file (.), which is obviously not what we want.

Because our purpose is to explain ${var}, this is enough, so the above procedure will not be amended.

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

Let's analyze the command echo $ (LS) to understand what the so-called command substitution means:
Shell scans the command line again, found the $ (CMD) structure, the $ (cmd) in the cmd executed once, get its standard output, and then put this output to the original command echo $ (LS) in the position of $ (LS), that is replaced by $ (LS), and then execute 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, but 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 all executed for a sequence of commands, but differ:
A, () just reopen a sub shell to execute on a sequence of commands
b,{} executes on a string of commands in the current shell
C, () and {} All put a string of commands inside the brackets, and the commands are separated by the;
D, () The last command can be without a semicolon
e,{} Last command to be separated by a semicolon
There must be a space between the first command and the opening parenthesis of f,{}
The commands in G, () do not have to have spaces with parentheses
The redirection of one of the commands inside the brackets of H, () and {} only affects the command, but the redirection outside the parentheses affects all the commands in 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 footsteps:

(
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 the ${var:-string} with a string in the command line, or the variable var is not empty, replace the ${var:-string with the value of the variable 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, that is, b
B
$

The replacement rule for ${var:=string} is the same as ${var:-string}, but the difference is ${var:=string} if VAR is null, replace ${var:=string} with string, Assign string to variable var:


$ echo $newvar

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

A common use for ${var:=string} is to determine whether a variable is assigned a value, or to assign it a default value if it is not.
For example, set the default editor:
PHP Code:
Echo Your use editor: ${editor:=/bin/vi}

B,${var:+string}
The substitution rule for ${var:+string} is the opposite of the above, that is, if Var is not empty, it is replaced with a string, and if Var is empty, it is not replaced or substituted for the value of VAR, or null value. (because 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 NULL, replace the ${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 exits from the script. We can use this attribute to check whether the value of the variable is set.
$ newvar=
$ echo ${newvar:? Do not set Newvar value}
Bash:newvar: No value set for Newvar
$ newvar=a
$ echo ${newvar:? Do not set Newvar value}
A
$

Supplemental extension: In these five substitution structures, string is not necessarily constant, and can be used for the value of another variable or the output of a command.
$ 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 in accordance with the C-language operator, which means that any operator conforming to C can be used in $ ((exp)) or even a three-mesh operator.
Note: This extended calculation is an integer-type calculation and does not support floating-point types. If logically, the expression exp is 1 and 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 shows that this extended operation is very powerful.

6. Four pattern matching replacement structure: ${var%pattern},${var%%pattern},${var#pattern},${var# #pattern}
The meaning of these four structures is that ${var%pattern} and ${var%%pattern} 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 the use of wildcard characters in pattern to have the longest and shortest match, otherwise there is no longest shortest matching points.

Pattern in the structure supports wildcards, * represents 0 or more arbitrary characters,? represents 0 or one arbitrary character, [...] Matches the characters inside the brackets, [!...] Represents a character that does not match the inside bracket.
$ 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 are expanded to produce a pat‐
Tern just as in pathname expansion. Parameter is expanded and
The longest match of pattern against it value is replaced with
String. If pattern begins with/, all matches of pattern are
Replaced with string. Normally only the ' a '
Replaced. If pattern begins and #, 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 are deleted and the/fol‐
Lowing is omitted. If parameter is @ or *, the sub‐
Stitution operation is applied to all 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 to each 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 a pair of parentheses inside the expression, the GNU document indicates that EXPR1 support Shell arithmetic;expr2 is not 0 o'clock, EXPR3 is assigned and statement execution. It's a hassle, and it takes time to figure out what a shell arithmetic is. Actually word, support the digital condition. Like what:

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

Will output 0 1 2 3 (with line change Oh ~ ~ ~ ~)

2, Mathematical expression

(()) and $ (())

(()) The use of the same as let, there is no need to explain it ~ ~ ~

$ (()) 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

(): A parentheses

In the For loop, the same as the C syntax.

Or a subroutine that returns the return value of the entire expression inside. The variables inside are local, and the modifications 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 is not what the horse meant.

[]: a square bracket, which is a bash command, can be found in the man manual, as in test, where you can see a lot of usage in the manual. For example,-b-c-gt-eq a lot of what, but also useful.-A representation with,-o representations, or so on

[[]]: One pair of brackets is a reinforced version of the square bracket, then the Shell's reserved word, which supports the | | && and so on these symbols. I usually like to use this.

There are also relatively complex {}

Several uses, distinguishing variables, such as:

VAR=ABCD; Echo ${VAR}EFG;

That way, Bash doesn't think the variable is VAREFG.

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

code block. To differentiate the code, but with () there is a difference, 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 Final supplement

2. (())

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

3.< () and > ()

Process generation, you can read the execution result of the command as a file
For example, comm usually need sort before, so that's it. Comm < (sort 1.lst) < (sort 2.lst)
or paste < (cut-t2 file1) < (cut-t1 file1)
, similar to pipes, but supports multiple inputs.

4.$ ()

$ (cmd) execution of CMD results, such as CMD is echo ls, then is executed LS, such as file$ (which bash), which bash results are/bin/bash, so file $ (which bash) equals file/bin/ Bash. If you are $ (LS) and you have only a B two files in your current directory, then you are performing a B, and then the system prompts you that the command is not found.

5.$ (())

An expression extension, similar to (()), but this is a bit different, $ (()) cannot be directly $ ((b++)), B=1;echo $ ((++b)) then B is equal to 2, and the display is 2,b=1;echo $ ((b++)) at which point B equals 2, showing 1.

6.[] and [[]]

[] is test,[] and [[]] are conditional expressions, but [[]] have higher fault tolerance than [], if A is empty, then [$a-eq 0] will have an error, but [[$a-eq 0]] will not, so it is common to use [[]] or a ["$a"-eq 0],[[]] supported work can also be more than [], for example [[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 bit of 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 is now not recommended for use

8.{}

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

9.${}

Variable, with a lot of usage, you can view man bash.
Write these first, and then think of the next add it.

Add: () is also an array of assignments, 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, which is summarized as follows:

1. Symbol $ after bracket

${a} The value of variable A, which can omit curly braces without causing ambiguity.
$ (CMD) command substitution, the result is the output of the shell command cmd, and the ' cmd ' effect is the same, although some shell versions do not support the $ () Form of command substitution, such as tcsh.
$ (exp) and the ' expr exp ' effect, calculates 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, or even the three-mesh operator and the logical expression.

2. More than one command execution

(CMD1;CMD2;CMD3) A new sub-shell sequence executes the command cmd1,cmd2,cmd3, separated by semicolons, and the last command can have no semicolon.
{cmd1;cmd2;cmd3;} In the current shell Order execute command CMD1,CMD2,CMD3, separate the commands with semicolons, the last command must have a semicolon, and the first command and the left parenthesis must be separated by a space.
for {} and (), the redirection character in parentheses affects only the command, and the redirection outside the parentheses affects all the commands in parentheses.

3. Special use of double brackets

(()) enhances the use of parentheses, which is often used for arithmetic operation comparisons. Variables in double brackets may not use the $ symbol prefix, so long as the expressions in parentheses conform to the C-language operation rules and allow multiple expressions to be separated by commas.
For example, you can use for direct for ((i=0;i<5;i++)) If you do not use double brackets, 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].
[[]] enhances the use of square brackets and is often used for comparisons of strings. Used primarily for conditional testing, expressions in double brackets can be used with &&, | | |,, >, and C language syntax.
For example, you can directly use if [[$a!= 1 && $a!= 2]], if the double brackets are not applicable, if [$a-ne 1] && [$a!= 2] or if [$a-ne 1-a $a!= 2] .

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.