Braces and parentheses in the shell

Source: Internet
Author: User
Tags echo command

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 once, finds the $ (CMD) structure, executes the cmd in $ (cmd) once, obtains its standard output, and then places the output in the original command echo$ (LS) in the $ (LS) position, that is, replace the $ (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, only the standard output is replaced:
$ var=$ (cat D) # # #文件d在当前目录不存在
CAT:D: No file or directory
$ echo $var

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

3. A string of commands to execute () 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$var1>a;echo $var 2;} # # #输出test1被重定向到文件a中,
Test2 # # #而test2输出则仍输出到标准输出中.
$ Cat A
Test1
$ {Var1=test1;var2=test2;echo $var 1;echo$var2;} >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 ${newvar:-a} in the previous command line was replaced with a

$ newvar=b
$ echo${newvar:-a}## #变量newvar的值不为空时, ${newvar:-b} In this command line is replaced with $newvar, which is 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), ${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 *}

$

Some of the supernatural powers of ${} in the shell

Suppose we define a variable as:
File=/dir1/dir2/dir3/my.file.txt
We can replace each other with ${} to get different values:
${file#*/}: Take out the first/its left string: dir1/dir2/dir3/my.file.txt
${file##*/}: Take out the last/and left string: my.file.txt
${file#*.} : Take out the first one. And the string to the left: file.txt
${file##*.} : Take out the last one. And the string to the left: txt
${file%/*}: Take off the last bar/its right string:/dir1/dir2/dir3
${file%%/*}: Remove the first/its right string: (null value)
${FILE%.*}: Take off the last one. And the string to the right:/dir1/dir2/dir3/my.file
${FILE%%.*}: Take out the first one. And the string to the right:/dir1/dir2/dir3/my
The methods of memory are:

# is to remove the left side (on the plate # on the left of the $)
% is removed to the right (on the plate% on the right of the $)
The single symbol is the minimum match, and the two symbol is the maximum match.

 

${file:0:5}: Extract the leftmost 5 bytes:/dir1
${file:5:5}: Extracts the 5th byte to the right of 5 consecutive bytes:/dir2
We can also replace strings in variable values:
${file/dir/path}: Change the first dir to path:/ Path1/dir2/dir3/my.file.txt
${file//dir/path}: Swap all dir for Path:/path1/path2/path3/my.file.txt

with ${} also available for Different variable state assignments (no setting, null value, non-null value):
${file-my.file.txt}: If the $file is null, use My.file.txt as the default value. (Reservation not set and non-null value)
${file:-my.file.txt}: If the $file is not set or null, use My.file.txt as the default value. (leave non-null values)
${file+my.file.txt}: Use My.file.txt as the default value regardless of the $file value. (no value is reserved)
${file:+my.file.txt}: Use My.file.txt as the default value unless the $file is a null value. (leave null value)
${file=my.file.txt}: If $file is not set, use My.file.txt as the default and define the $file as a non-null value. (leave null and non-null values)
${file:=my.file.txt}: If the $file is not set or null, use My.file.txt as the default and define the $file as a non-null value. (leave non-null values)
${file?my.file.txt}: If the $file is not set, the My.file.txt output to STDERR. (leave null and non-null values))
${file:?my.file.txt}: If the $file is not set or null, the my.file.txt output to STDERR. (leave non-null values)

Also, ${#var} can calculate the length of the variable value:
${#file} can get 27 because/dir1/dir2/dir3/my.file.txt is just 27 bytes ...

Article excerpt from: http://blog.sina.com.cn/s/blog_4a2a29f00100o2os.html thank Bo friends to share O (∩_∩) o~

Braces and 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.