[ Previous | Next | Table of Contents | Index | Library Home | Legal | Search ]

System User's Guide: Operating System and Devices


Command Substitution in the Korn Shell or POSIX Shell

The Korn Shell, or POSIX Shell, enables you to do 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, perform the following:

$(command)

or, for the backquoted version, use:

`command`

Note: Although the backquote syntax is accepted by ksh, it is considered obsolete by the XPG4 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 new-line 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)) seconds

produces the following result:

Each hour contains 3600 seconds

The Korn shell or POSIX shell removes all trailing new-line characters when performing command substitution. For example, if your current directory contains the file1, file2, and file3 files, the command:

echo $(ls)

removes the new-line characters and produces the following output:

file1 file2 file3

To preserve new-line characters, insert the substituted command in " ":

echo "$(ls)"


[ Previous | Next | Table of Contents | Index | Library Home | Legal | Search ]