11.11. Command Substitution
Command substitution is used when assigning the output of a command to a variable, or when substituting the output of a command into a string. The Bourne and C shells use backquotes to perform command substitution. The Korn shell does allow the backquote format (calling it "obsolescent"), but placing the command in parentheses is the preferred method because it has simpler quoting rules and makes nesting commands easier.
FORMAT
`Unix/Linux command` # Old method with backquotes
$(Unix/Linux command) # New method
Example 11.57.
(Old Way)
1 $ print "The hour is `date +%H`"
The hour is 09
2 $ name=`nawk –F: '{print $1}' database`
$ print $name
Ebenezer Scrooge
3 $ ls `ls /etc`
shutdown
4 $ set `date`
5 $ print $*
Sat Oct 13 09:35:21 PDT 2004
6 $ print $2 $6
Oct 2004
EXPLANATION
The output of the date command is substituted into the string. The output of the nawk command is assigned to the variable name, and displayed. The output of the ls command, enclosed in backquotes, is a list of files from the /etc directory. The filenames will be arguments to the first ls command. All files with the same name in /etc as are in the current directory are listed. The set command assigns the output of the date command to positional parameters. Whitespace separates the list of words into its respective parameters. The $* variable holds all of the parameters. The output of the date command was stored in the $* variable. Each parameter is separated by whitespace. The second and sixth parameters are printed.
The ksh alternate for using backquotes in command substitution is presented in Example 11.58.
Example 11.58.
(The New ksh Way)
1 $ d=$(date)
$ print $d
Sat Oct 20 09:35:21 PDT 2004
2 $ line = $(< filex)
3 $ print The time is $(date +%H)
The time is 09
4 $ machine=$(uname –n)
$ print $machine
jody
5 $ dirname="$(basename $(pwd))" # Nesting commands
$ print $dirname
bin
EXPLANATION
The date command is enclosed within parentheses. The output of the command is returned to the expression, assigned to the variable d, and displayed. The input from the file is assigned to the variable line. The < filex notation has the same effect as `cat filex`. Command substitution is performed within the parentheses when the parentheses are preceded with a dollar sign. The UNIX date command and its hour argument, +%H, are enclosed within parentheses. Command substitution is performed, and the results are placed within the print string. Command substitution has been performed. The output of the UNIX uname command is assigned to the variable machine. To set the variable dirname to the name (only) of the present working directory, command substitution is nested. The pwd command is executed first, passing the full pathname of the present working directory as an argument to the UNIX command basename. The basename command strips off all but the last element of a pathname. Nesting commands within backquotes is not allowed.
|