The role of (), (()), [], [[]], {} in Linux Shell

Introduction The commands in the parentheses will be executed in sequence by opening a new subshell, so the variables in the parentheses cannot be used by the rest of the script. Multiple commands in the brackets are separated by semicolons, the last command can be without a semicolon, and there is no need to have a space between each command and the brackets.
The role of (), (()), [], [[]], {} in Linux Shell The role of (), (()), [], [[]], {} in Linux Shell

1. Parentheses, parentheses ()
1. Single parentheses ()
① command group. The commands in the parentheses will be executed in order by opening a new subshell, so the variables in the parentheses cannot be used by the rest of the script. Multiple commands in the brackets are separated by semicolons, the last command can be without a semicolon, and there is no need to have a space between each command and the brackets.

②Command replacement. It is equivalent to cmd. When the shell scans the command line and finds the structure, it will execute the (cmd) structure, then execute the cmd in (cmd) once to get its standard output, and then put this output in the original command. Some shells do not support, such as tcsh.

③Used to initialize the array. Such as: array=(abcd)2, double parentheses (( ))① integer expansion. This extended calculation is an integer calculation and does not support floating point. ((exp)) The structure expands and calculates the value of an arithmetic expression. If the result of the expression is 0, then the exit status code returned is 1, or "false", and the expression returned by a non-zero value The exit status code will be 0, or "true". If it is a logical judgment, the expression exp is true if it is 1, and if it is false, it is 0. ②As long as the operators and expressions in parentheses conform to the C language operation rules, they can be used in ((exp)), even ternary operators. When performing different carry (such as binary, octal, hexadecimal) operations, all output results are automatically converted to decimal. For example: echo((16#5f)) results in 95 (hexadecimal to decimal) ③It is possible to redefine the variable value simply by using (( )), such as a=5; ((a++)) can redefine $a as 6

④It is often used for comparison in arithmetic operations. The variables in double brackets do not need to use the symbol prefix. Multiple expressions within brackets are separated by commas. As long as the expression in the parentheses conforms to the C language operation rules, for example, you can directly use for((i=0;i<5;i++)). If you do not use double parentheses, it is foriin'seq04' or foriin0..4. Another example is if ((i<5)) can be used directly, if double brackets are not used, it is if [$i -lt 5 ].

2. Square brackets, square brackets []
1. Single square brackets []
①The internal command of bash, [and test are equivalent. If we do not specify the absolute path, we usually use the commands that come with bash. The left square bracket in the if/test structure is the command identifier for calling test, and the right square bracket is used to judge the closing condition. This command takes its parameters as a comparison expression or as a file test, and returns an exit status code based on the result of the comparison. The closing bracket is not necessary in the if/test structure, but it is required in the new version of Bash.

②The only comparison operators available in Test and [] are == and !=, both of which are used for string comparison and cannot be used for integer comparison. Integer comparison can only use the form -eq, -gt. Neither the string comparison nor the integer comparison supports the greater than sign and the less than sign. If you really want to use it, you can use the escaped form for string comparison. If you compare "ab" and "bc": [ab <bc ], the result is true, that is, the return status is 0. The logical AND and logical OR in [] are represented by -a and -o.

③Character range. Used as part of a regular expression to describe a range of characters to match. Regulars cannot be used in brackets for test purposes.

④ In the context of an array structure, square brackets are used to refer to the number of each element in the array.

2. Double square brackets [[ ]]
①[[ is a keyword of the bash programming language. Not a command, the [[ ]] structure is more general than the [] structure. All characters between [[ and]] will not have file name expansion or word splitting, but parameter expansion and command substitution will occur.

②Support string pattern matching, even support shell regular expression when using =~ operator. When comparing strings, you can use the one on the right as a pattern, not just a string, such as [[ hello == hell? ]], the result is true. [[ ]] matches strings or wildcards without quotation marks.

③Using [[ ... ]] conditional judgment structure instead of [...] can prevent many logic errors in the script. For example, the &&, ||, <, and> operators can normally exist in the [[ ]] conditional judgment structure, but if they appear in the [] structure, an error will be reported. For example, if [[ $a != 1 && $a != 2 ]] can be used directly, if double brackets are not applicable, then if [$a -ne 1] && [$a != 2] or if [$a -ne 1 -a $a != 2 ].

④bash treats the expression in the double brackets as a single element and returns an exit status 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, curly braces {}
1. Conventional usage
①Expanded braces. (Globbing) will expand the file name in braces. In the braces, no white space is allowed unless the white space is quoted or escaped. The first type: expand the comma-separated file list in braces. For example, touch {a,b}.txt will result in a.txt b.txt. The second type: expand the list of files in the curly brackets separated by dots (..), such as: touch {a..d}.txt The result 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 
block, also known as internal group, this structure actually creates an anonymous function. Unlike the commands in the parentheses, the commands in the braces will not open a new subshell to run, that is, the variables in the parentheses can still be used in the rest of the script. The commands in parentheses are separated by semicolons, and the last one must also have a semicolon. There must be a space between the first command of {} and the opening parenthesis.

2. Several special replacement structures
${var:-string},${var:+string},${var:=string},${var:?string} 
①${var:-string} and ${ var:=string}: If the variable var is empty, replace ${var:-string} with string in the command line; otherwise, if the variable var is not empty, replace ${var: with the value of the variable var: -string}; The replacement rule for ${var:=string} is the same as ${var:-string}, the difference is that ${var:=string} If var is empty, replace ${ with string While var:=string}, assign string to variable var: ${var:=string} A very common usage is to determine whether a variable is assigned a value, and if not, assign a default value to it.

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

③The replacement rule for ${var:?string} is: if the variable var is not empty, replace ${var:?string} with the value of the variable var; if the variable var is empty, output string to the standard error. And exit from the script. We can use this feature to check whether the value of the variable is set.

Supplementary extension: In the above five substitution structures, string is not necessarily a constant value, and the value of another variable or the output of a command can be used.

3. Four kinds of pattern matching replacement structure
Pattern matching memory method:

#是脱脱Left (on the keyboard # is on the left of the $)
% is removed on the right (% is on the right of the $ on the keyboard)
The single symbol in # and% is the minimum match, and two identical symbols are the maximum match.
${var%pattern},${var%%pattern},${var#pattern},${var##pattern} The 
first pattern: ${variable%pattern}, in this pattern, the shell is in the variable Search to see if it is the end of the pattern given, if it is, remove the contents of the variable from the command line with the shortest matching pattern on the right

The second mode: ${variable%%pattern}. In this mode, the shell looks in the variable to see if it is the end of the given pattern. If it is, remove the contents of the variable from the command line and the longest on the right Match pattern

The third pattern: ${variable#pattern} In this pattern, the shell looks in the variable to see if it starts with the given pattern pattern. If it is, remove the contents of the variable from the command line with the shortest matching pattern on the left

The fourth mode: ${variable##pattern} In this mode, the shell looks in the variable to see if it is the end of the given pattern. If it is, remove the contents of the variable from the command line with the longest on the right Matching mode These four modes will not change the value of variable. Among them, only when the * matching symbol is used in the pattern, there is a difference between% and %%, # and ##. The pattern in the structure supports wildcards, * means zero or more arbitrary characters,? Means matching only one arbitrary character, [...] means matching the characters in the brackets, [!...] means not matching the brackets Characters inside.

# 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/pattern},${var//pattern/pattern} The 
first pattern: ${var:num}, in this mode, the shell is in var Extract all characters from the numth character to the end. If num is positive, start from 0 on the left; 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}, where num1 is the position and num2 is the length. Indicates that the substring of length $num2 is extracted from the $num1 position of the $var string. Cannot be negative.

The third pattern: ${var/pattern/pattern} means to replace the first matching pattern of the var string with another pattern.

The fourth pattern: ${var//pattern/pattern} means to replace all matching patterns 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) ${a} Variable For the value of a, the braces can be omitted if it does not cause ambiguity.

(2) The $(cmd) command substitution has the same effect as `cmd`. The result is the output of the shell command cmd. Some Shell versions do not support the command substitution in the form of $(), such as tcsh.

(3)$((expression)) has the same effect as `exprexpression`. It calculates the value of the mathematical expression exp, where exp only needs to conform to the operation rules of the C language, and even ternary operators and logical expressions can be calculated.

5. Use
multiple commands to execute
①Single parentheses, (cmd1;cmd2;cmd3) open a new subshell to execute commands cmd1, cmd2, cmd3 in order, separated by semicolons, there can be no division after the last command number.

②Single braces, {cmd1;cmd2;cmd3;} execute the commands cmd1, cmd2, cmd3 in the current shell sequence, separated by semicolons, the last command must be followed by a semicolon, the first command and the left The brackets must be separated by spaces.

For {} and (), the redirection character in the brackets only affects the command, while the redirection character outside the brackets affects all the commands in the brackets. Linux should be learned like this

Guess you like

Origin blog.csdn.net/Linuxprobe18/article/details/111942126