Command substitution in the Korn shell or POSIX shell
The Korn Shell, or POSIX Shell, lets you perform command substitution. In command substitution, the shell executes a specified command in a subshell environment and replaces that command with its output.
To execute command substitution in the Korn shell or POSIX shell, type
the following:
$(command)or, for the backquoted version,
type the following: `command`Note: 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.The shell expands the command substitution by executing command in
a subshell environment and replacing the command substitution (the text of command plus
the enclosing $( ) or backquotes) with the standard output
of the command, removing sequences of one or more newline characters at the
end of the substitution.
In the following example, the
$( ) surrounding the command
indicates that the output of the whoami command is substituted: echo My name is: $(whoami)You can perform the same command substitution with:
echo My name is: `whoami`The output from both examples for user
dee is: My name is: dee You can also substitute arithmetic expressions by enclosing them in
(
). For example, the command: echo Each hour contains $((60 * 60)) secondsproduces
the following result: Each hour contains 3600 secondsThe Korn shell or POSIX shell removes all trailing newline characters when
performing command substitution. For example, if your current directory contains
the file1, file2, and file3 files,
the command:
echo $(ls)removes the newline characters
and produces the following output: file1 file2 file3To preserve newline characters, insert the substituted command in
"
": echo "$(ls)"