I am confused by the usage of brackets, parentheses, curly braces in Bash, as well as the difference between their double or single forms. Is there a clear explanation?
Bash – How to use double or single brackets, parentheses, curly braces
bashsyntax
Related Topic
- Html – Single vs Double quotes (‘ vs “)
- Php – the difference between single-quoted and double-quoted strings in PHP
- Scala – the formal difference in Scala between braces and parentheses, and when should they be used
- Bash – Difference between single and double quotes in Bash
- Bash – When do we need curly braces around shell variables
- Bash – Difference between parentheses and brackets in Bash conditionals
- Bash – Difference between single and double square brackets in Bash
- C++ – Why is list initialization (using curly braces) better than the alternatives
Best Answer
In Bash,
test
and[
are shell builtins.The double bracket, which is a shell keyword, enables additional functionality. For example, you can use
&&
and||
instead of-a
and-o
and there's a regular expression matching operator=~
.Also, in a simple test, double square brackets seem to evaluate quite a lot quicker than single ones.
The braces, in addition to delimiting a variable name are used for parameter expansion so you can do things like:
Truncate the contents of a variable
Make substitutions similar to
sed
Use a default value
and several more
Also, brace expansions create lists of strings which are typically iterated over in loops:
Note that the leading zero and increment features weren't available before Bash 4.
Thanks to gboffi for reminding me about brace expansions.
Double parentheses are used for arithmetic operations:
and they enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability.
Single brackets are also used for array indices:
Curly brace are required for (most/all?) array references on the right hand side.
ephemient's comment reminded me that parentheses are also used for subshells. And that they are used to create arrays.