SoFunction
Updated on 2025-03-02

Analysis of the difference between small brackets, brackets and curly brackets in shell

1. Small brackets, round brackets ()

1. Single brackets ()

① Command group. The commands in brackets will be executed in sequence, so the variables in brackets cannot be used by the rest of the script. Multiple commands in brackets are separated by semicolons. The last command can have no semicolons, and there is no need to have spaces between each command and bracket.

② Command replacement. It is equivalent to `cmd`. The shell scans the command line and discovers the $(cmd) structure. It executes the cmd in $(cmd) once to obtain its standard output, and then puts this output into the original command. Some shells do not support, such as tcsh.

③ Used to initialize the array. For example: array=(a b c d)

2. Double brackets (( ))

① Integer expansion. This extended calculation is an integer type calculation and does not support floating point type. ((exp)) structure extends and calculates the value of an arithmetic expression. If the result of the expression is 0, the returned exit status code is 1, or is "false", while the exit status code returned by a non-zero expression will be 0, or is "true". If it is a logical judgment, the expression exp is true and the expression exp is 1, and the expression exp is false is 0.

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

③ You can also redefine variable values ​​by simply using (( )), such as a=5; ((a++)) You can redefine $a to 6

④ It is often used for arithmetic comparisons. Variables in double brackets can not use the $ symbol prefix. Multiple expressions are supported in brackets with commas to separate. As long as the expression in the bracket complies with the C operation rules, for example, you can use for((i=0;i<5;i++)) directly. If you do not use double brackets, it is for i in `seq 0 4` or for i in {0..4}. For example, you can use if (($i<5)) directly. If you do not use double brackets, it is if [ $i -lt 5 ].

2. Square brackets, square brackets[]

1. Single brackets []

①Bash's internal command, [is equivalent to test. If we do not use absolute path indication, we usually use the commands that come with bash. The left middle bracket in the if/test structure is the command identifier for calling test, and the right middle bracket is the judgment of closing the condition. This command takes its parameters as a comparison expression or as a file test, and returns an exit status code based on the comparison results. The if/test structure does not require the closing bracket, but the new version of Bash requires this.

②The only comparison operators available in Test and [] are == and !=. Both are used for string comparison and cannot be used for integer comparison. Integer comparison can only use the form -eq and -gt. Neither string comparison nor integer comparison support greater than or less. 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. Logic and logic in [ ] or used -a and -o.

③ Character range. Used as part of a regular expression, describing a matching character range. For test purposes, the regular cannot be used in brackets.

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

2. Double brackets[[ ]]

①[[ is the keyword of the bash programming language. It is not a command, the [[ ]] structure is more general than the [ ] structure. No file name extension or word segmentation occurs for all characters between [[ and ]], but parameter extension and command replacement will occur.

② Supports pattern matching of strings, and even supports shell regular expressions when using the =~ operator. 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. Match strings or wildcards in [[ ]] without quotation marks.

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

④Bash treats the expression in double brackets as a separate 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. Regular usage

① Expand the braces. (globbing) will expand the file name in braces. In braces, no blank is allowed unless the blank is referenced or escaped. The first type: expand the comma-segmented file list in braces. For example, touch {a,b}.txt The result is . The second type: expand the file list in the braces divided by dots (..), for example: touch {a..d}.txt The result is

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

② Code block, also known as internal groups, actually creates an anonymous function. Unlike the commands in brackets, the commands in braces will not open a new subshell to run, that is, the rest of the script can still use variables in brackets. The commands in brackets 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 bracket.

2. Several special replacement structures

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

${var:-string} and ${var:=string}:If the variable var is empty, it will be replaced by string on the command line.${var:-string}, otherwise when the variable var is not empty, the value of the variable var is replaced${var:-string};for${var:=string}Replacement rules and${var:-string}It's the same, the difference is${var:=string}If var is empty, replace it with string.${var:=string}At the same time, assign string to the 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.

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

${var:?string}The change rule is: If the variable var is not empty, the value of the variable var is replaced.${var:?string};If the variable var is empty, string is output to 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 alternative structures, string may not be constant, and the value of another variable or the output of a command can be used.

This is the end of this article about the differences between shell brackets, brackets and braces. For more information about shell brackets, brackets and braces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!