MH & nmh: Email for Users & Programmers

May, 2006

Shell Command Substitution

A pair of backquotes (``) does command substitution in UNIX shells. This is really useful -- it lets you use the output from one command as arguments to another command. Here's an example. (If you have the -sequence switch in your MH profile, use pick -list below, instead of just pick):

    $ pick -from yourfriend
    1
    2
    113
    227
    $ scan `pick -from yourfriend`
       1  01/28 yourfriend         Test message<<Hi!>>
       2  01/28 yourfriend         Another test<<Well, this is anot
     113+ 02/14 yourfriend         The latest on my project<<It's g
     227  03/03 yourfriend         <<I can't get MH to work so I'm
    $
    
The first command line runs pick; the output goes to the screen. The second command line has the same pick command on it, but the backquotes tell the shell to use the output of the pick command as arguments to the scan command. The scan command scans the messages that pick found. (You might be wondering about the difference between the "vertical" output from pick, and the "horizontal" way that people usually type arguments on a command line. The shell handles this with no problems. Inside backquotes, both a newline and a space are argument separators.)

The Korn shell also has command substitution operators that works like backquotes but may be easier to use: $( and $). For example, you could type the previous pick example like this:

    $ scan $(pick -from yourfriend$)       ...Korn shell only
    
The big advantage of the Korn shell syntax is that $( and $) are easy to nest (when you want to do command substitution on the result of a command substitution). You can nest pairs of backquotes, but the syntax is too ugly to print :-) -- use a temporary shell variable instead.