Command substitution

Command substitution allows the output of a command to replace the command itself.

Command substitution occurs when a command is enclosed as follows:


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 can 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.

Command substitutions can be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes.

If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results.

Process substitution operators:



command can be any command that produces output on stdout. Bash execs the command, creates a named pipe from the output, and replaces the operator with the name of that pipe. You can then read stdout from that pipe as you would from a regular file. When execution is finished, the named pipe is removed automatically.


Diff the output of two processes:

$ diff <(/sbin/lsmod) <(ssh sys1 /sbin/lsmod)

To do this without using process substitution would require using a temporary file.

Merge and sort a selection of files:

$ sort -m <(zcat file.1.gz) <(zcat file.2.gz) <(zcat file.3.gz) ... | gzip -c > merged.gz


BASH Syntax
Wikipedia: Process substitution
Introduction to Named Pipes - Linux Journal

© Copyright 1999-2015
Some rights reserved