From the Command Substitution subsection in the POSIX standard:
Command substitution allows the output of a command to be substituted in place of the command name itself.
Command substitutions allow for a handy way of making use of a command's output without the need for first writing it to a temporary file and then reading it in from that file. This is best done if the command's output is a short string on a single line.
Some people use command substitutions to collect output from a command even though the amount of output may be a multi-line document. This is generally not a good way of using command substitution. Instead, the standard Unix idiom of passing data between processing stages using pipelines or temporary files should be used.
Examples of command substitutions that I use:
For example, to figure out whether the current user is executing the script as root:
if [ "$( id -u )" -ne 0 ]; then
echo 'This script requires root privileges, re-run with sudo' >&2
$(id -u) command substitution will be substituted with the output of
id -u, which will return the UID (an integer) of the current user.
Another example. I'm using GnuPG to sign
git commits. For GnuPG to work properly, I need to set
GPG_TTY to the name of the current terminal device in my interactive shell's initialization file. I do this with
export GPG_TTY="$( tty )"
GPG_TTY to something like
/dev/ttyp4 depending on what the current terminal device is in the shell session.
Another example. I have a script that has to treat running on a Solaris machine as a special case:
case "$( uname -s )" in
# code specific for Solaris
# code for all other Unix platforms
Another example. The
getconf PATH command returns the "default path" for the current system. I use it under some circumstances to reset the
PATH variable to a "sane default" value:
PATH="$( getconf PATH )"