7.7 Command Substitution

7.7 Command Substitution

The Bourne shell can redirect a command's standard output back to the shell's own command line. That is, you can use a command's output as an argument to another command, or you can store the command output in a shell variable. You do this by enclosing a command in backquotes (`).

Here's an example that stores a command inside a variable, FLAGS:

#!/bin/sh
FLAGS=`grep ^flags /proc/cpuinfo | sed 's/.*://' | head -1`
echo Your processor supports:
for f in $FLAGS; do
    case $f in
        fpu)    MSG="floating point unit"
                ;;
        3dnow)  MSG="3DNOW graphics extensions"
                ;;
        mtrr)   MSG="memory type range register"
                ;;
        *)      MSG="unknown"
                ;;
    esac
    echo $f: $MSG
done

The second line contains the command substitution, in bold type. This example is somewhat complicated, because it demonstrates that you can use both single quotes and pipelines inside the command substitution backquotes. The result of the grep command is sent to the sed command (more about sed later), which removes anything matching the expression .*:, and the result of sed is then passed to head.

It's too easy to go overboard with command substitution. For example, don't use `ls` in a script, because using the shell to expand * is faster. Also, if you want to invoke a command on several filenames that you get as a result of a find command, you may want to consider using a pipeline to xargs rather than command substitution (see Section 7.10.4).