oreilly.comSafari Books Online.Conferences.


Unix Power Tools
The () Subshell Operators

by Tim O'Reilly and Jerry Peek

A useful shell trick is to use parentheses, (), to group commands.

Combining Several Commands

The output of the entire group can be passed together into a single pipeline. For example:

$ (cat file1; echo .bp; cat file2) | nroff

This will interpose the nroff .bp (break page) request between two files to be formatted. *

Parentheses are also very useful in the Bourne shell if you want to put an entire sequence of commands separated by semicolons into the background. In the C shell, the command line below will go immediately into the background.

$ nroff -ms file1; nroff -ms file2 &

But in the Bourne shell, the background request (&) will only apply to the second command, forcing you to wait for completion of the first job before you get back the system prompt. To get right back to work, you can type:

$ (nroff -ms file1; nroff -ms file2) &

Temporary Change of Directory and Environment

The parentheses start a subshell. Commands that run between the parentheses won't affect the parent shell's environment. For instance, to run a command in another directory without changing your active shell's current directory :

% pwd
% (cd somewhere-else; nroff -ms file1 > file.out) &
[1] 22670
% pwd

The file file.out will be created in the somewhere-else directory.

* If you're using only cat and a single echo, you can use this command instead:

$ echo .bp | cat file1 - file2 | nroff

The cat - option tells cat to read its standard input (in this case, from the pipe and the echo) at that point. nroff gets exactly the same input.

Back More Unix Power Tools


Linux Online Certification

Linux/Unix System Administration Certificate Series
Linux/Unix System Administration Certificate Series — This course series targets both beginning and intermediate Linux/Unix users who want to acquire advanced system administration skills, and to back those skills up with a Certificate from the University of Illinois Office of Continuing Education.

Enroll today!

Linux Resources
  • Linux Online
  • The Linux FAQ
  • Linux Kernel Archives
  • Kernel Traffic

  • Sponsored by: