UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 13.2 One Argument with a cat Isn't Enough Chapter 13
Redirecting Input and Output
Next: 13.4 Problems Piping to a Pager
 

13.3 Send (only) Standard Error Down a Pipe

A vertical bar character (|) on a command line pipes the standard output of a process to another process. How can you pipe the standard error, not the standard output? You might want to put a long-running cruncher command in the background, save the output to a file, and mail yourself a copy of the errors. In the C shell, run the command in a subshell (13.7). The standard output of the command is redirected inside the subshell. All that's left outside the subshell is the standard error; the |& operator (13.5) redirects it (along with the empty standard output) to the mail (1.33) program:

% (cruncher > outputfile) |& mail yourname &
[1] 12345

Of course, you don't need to put that job in the background (1.26). If you want the standard output to go to your terminal instead of a text file, use /dev/tty (45.20) as the outputfile.

The Bourne shell gives you a lot more flexibility and lets you do just what you need. The disadvantage is the more complicated syntax (45.21). Here's how to run your cruncher program, route the stderr through a pipe to the mail program, and leave stdout going to your screen:

$ (cruncher 3>&1 1>&2 2>&3 3>&-) | mail yourname &
12345

To redirect stdout to an output file and send stderr down a pipe, try this:

$ (cruncher 3>&1 >outputfile 2>&3 3>&-) | mail yourname &
12345

- JP


Previous: 13.2 One Argument with a cat Isn't Enough UNIX Power ToolsNext: 13.4 Problems Piping to a Pager
13.2 One Argument with a cat Isn't Enough Book Index13.4 Problems Piping to a Pager

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System