Section 5.8. Command Substitution


[Page 178]

5.8. Command Substitution

A command surrounded by grave accents ( ` ) is executed and its standard output is inserted in the command in its place. Any newlines in the output are replaced by spaces. For example:

$ echo the date today is `date` the date today is Wed Feb 2 00:41:55 CST 2005 $ _ 


It's possible to do some crafty things by combining pipes and command substitution. For example, the who utility (described in Chapter 9, "Networking and the Internet") produces a list of all the users on the system, and the wc utility (described in Chapter 3, "GNU Utilities for Nonprogrammers") counts the number of words/lines in its input. By piping the output of who to the wc utility, it's possible to count the number of users on the system:

$ who             ...look at the output of who. posey    ttyp0   Jan 22 15:31   (blackfoot:0.0) glass    ttyp3   Feb  3 00:41   (bridge05.utdalla) huynh    ttyp5   Jan 10 10:39   (atlas.utdallas.e) $ echo there are `who | wc -l` users on the system there are 3 users on the system $ _ 


The result of command substitution may be used as part of another command. For example, the vim utility allows you to specify a list of files to be edited on the command line, which are then visited by the editor one after the other. The grep utility, described in Chapter 4, "GNU Utilities for Power Users" has a -l option that returns a list of all the files on the command line that contain a specified pattern. By combining these two features using command substitution, it's possible to specify using a single command that vim be invoked upon all files ending in ".c" that contain the pattern "debug":

$ vim `grep -l debug *.c` 





Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net