When should one use $( ) in defining variables
From the manual (man bash
):
$(
command)
or`
command`
Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution
$(cat
file)
can be replaced by the equivalent but faster$(<
file)
.When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by
$
,`
, or\
. The first backquote not preceded by a backslash terminates the command substitution. When using the$(
command)
form, all characters between the parentheses make up the command; none are treated specially.
The POSIX standard defines the $()
form of command substitution. $()
allows nested commands and looks better (legibility). It should be available on all Bourne shells.
You can read more on IEEE Std 1003.1, Shell Command Language, Section 2.6.3 Command Substitution.
At least one Unix, AIX, has documented that backticks are obsolete. From that link:
Although the backquote syntax is accepted by ksh, it is considered obsolete by the X/Open Portability Guide Issue 4 and POSIX standards. These standards recommend that portable applications use the $(command) syntax.
However, /bin/sh
does not have to be POSIX compliant. So there is still sometimes a case for backticks in the real world, as @Jeight points out.