Backquotes
Sometimes, redirecting output from a command is not quite what
you want to do. If you need to set the value of a variable to be
the output of a command, the mechanisms we have already met will
not work. As an example, suppose you wished to set a variable
YEAR to the current year. We can easily find the
current year using date . Either use the
formatting argument +"%Y" to
date (check this out from the manual page for
date ), or pipe the output through
cut .
$ date +"%Y"
2001
$ date | cut -f7 -d' '
2001
However, printing the output of date on your
terminal or sending it to a file will not allow it to be on the
right-hand side of the equals symbol in an assignment. If you
enclose a command in backquotes (` ), or alternatively
enclose it in $( and ) , it is executed
and its standard output becomes a string which is then passed to
the shell in place of the original command. This is known as
command substitution:
$ YEAR=`date +"%Y"`
$ YEAR=$( date +"%Y" )
As for double quotes, variable names preceded by a
$ symbol will be replaced by their values between
backquotes.
Worked example
Reset your shell prompt to the name of the shell followed by a
> symbol.
Solution: the variable SHELL holds
the name of the shell as an absolute pathname:
$ echo $SHELL
/usr/local/bin/sh
The command basename can be used to remove the
directory portion of a path name, so basename $SHELL
will extract the name of the shell you are using. Use backquotes to
turn the output from basename into a string, and
remember that > and the space, since they are
special symbols, must be quoted:
$ PS1=$( basename $SHELL )">
"
sh>
|