Command substitution
Last revision August 6, 2004
The result of any command, meaning whatever it would write to standard output, can be "captured" by the shell and used to set the value of a variable or as part or all of the arguments to another command. This is different from sending the output through a pipe to be the input of another command. Here, the output of one command becomes the arguments of another command, not the input file. This is called "command substitution".
Capturing the output of a command is requested by enclosing that entire command with its arguments in a set of matching backwards quote marks (`) (also called "accent" mark or "grave" mark). This is not the same character as the apostrophe or single quote, which slants forward (').
In captured output, all newline characters (end-of-line markers) are changed to blanks, so the lines in the captured output are joined into one long string of words. Empirical tests on pangea show that the total length of this captured string can be at least 50,000 bytes. Other Unix systems may have smaller limits. All should allow at least 4,000 bytes in command substitution captured strings.
The shell stores captured output in a temporary area of memory. Once you have captured the output of a command, of course you want to do something with it. You can assign the output to a variable, or use it as part or all of the arguments to another command.
Examples:
- If a file contains a list of names, you can assign the contents of that file
to a variable by capturing the output of a cat command that is listing
the file to standard output . Here is the kind of line you might use for that
in a shell script:
-
set names = ` cat file `
- You could use that captured list of names from the cat command
directly as the argument list to another command, such as finger:
-
finger ` cat file `
- You could tell the mv command to move all the files whose names
are listed in the file list to the new directory newdir
with this command:
-
mv `cat list` newdir