Previous Section  < Day Day Up >  Next Section

7.8. Command Substitution

When a command is enclosed in backquotes, it will be executed and its output returned. This process is called command substitution. It is used when assigning the output of a command to a variable or when substituting the output of a command within a string. All three shells use backquotes to perform command substitution.[2]

[2] The Korn shell allows backquotes for command substitution for upward compatibility, but provides an alternate method as well.

Example 7.34.

1   $ name=`nawk –F:  '{print $1}' database`

    $ echo $name

    Ebenezer Scrooge

2   $ set `date`

3   $ echo $*

    Fri Oct 22 09:35:21 PDT 2004

4   $ echo  $2 $6

    Oct 2004


EXPLANATION

  1. The nawk command is enclosed in backquotes. Command substitution is performed. The output is assigned to the variable name, as a string, and displayed.

  2. The set command assigns the output of the date command to positional parameters. Whitespace separates the list of words into its respective parameters.

  3. The $* variable holds all of the positional parameters. The output of the date command was stored in the $* variable. Each parameter is separated by whitespace.

  4. The second and sixth parameters are printed.

    Previous Section  < Day Day Up >  Next Section