[ Bottom of Page | Previous Page | Next Page | 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:


or, for the backquoted version, use:


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)) seconds

produces the following result:

Each hour contains 3600 seconds

The 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 file3

To preserve newline characters, insert the substituted command in " ":

echo "$(ls)"

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