Yuan Wen Yuan Wen - 3 months ago 9
Bash Question

In bash shell, how to classify the usage of (), (()),[], [[]] and {}?

I'm new to shell. And I'm a little bit confused with the usage of (),[],{} in shell script like

$()
,
[ [] ]
,
${}
and so on. I want to classify their usage to learn shell script more efficiently.

Answer

[ ] vs [[ ]] are test operators
See What's the difference between [ and [[ in bash? for a good overview on their differences.

$() is command substitution

$ echo "my hostname is: $(hostname)"
my uptime is: MYPC

$(( )) is arithmetic expansion

$ echo "$(( 5 + 5 ))"
10

${ }
This is used to refer to variables and avoid confusion over their name.

$ v="hello"
$ echo "$vbye"

$ echo "${v}bye"
hellobye

Also, it is used to reference array elements:

$ declare -A my_arr
$ my_arr[a]="hello"
$ echo "${my_arr[a]}"
hello

( ) and { } are also used as grouping commands

( ) runs in a subshell:

$ v=5
$ ( v=2; echo "$v" )
2
$ echo "$v"
5

Whereas { list, } does not:

$ v=5
$ { v=2; echo "$v"; }
2
$ echo "$v"
2