Shell Command Substitution

[previous] [next] [table of contents] [index]

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
$ 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.

[Table of Contents] [Index] [Previous: How Does Your System Execute Files?] [Next: Using Exit Status]

Last change $Date: 1999/10/10 05:14:05 $

This file is from the third edition of the book MH & xmh: Email for Users & Programmers, ISBN 1-56592-093-7, by Jerry Peek. Copyright © 1991, 1992, 1995 by O'Reilly & Associates, Inc. This file is freely available; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. For more information, see the file copying.htm.

Suggestions are welcome: Jerry Peek <>