Redirecting Error Messages



next up previous contents index
Next: WORKSTATION SETUP AND Up: Redirecting I/O and Previous: Combining I/O Redirection

Redirecting Error Messages

All Unix commands can have their input and output redirected. Our examples have shown commands using standard input and output. Commands that use standard error output require additional attention. A notable example is the C compiler's output which goes to standard error. For example, if you enter the command    

% cc myprog.c | more This fails.

the output will appear on the screen rather than going through more. To redirect both standard error output and standard output when using the C shell, add an ampersand (&) after the vertical bar |:
% cc myprog.c |& more Pipe both stderr and stdout in csh.

Similarly, if you want to send cc's output to the file err.file, place an ampersand after the right arrow >:

% cc myprog.c >& err.file Redirecting stderr in csh.

When using the Korn or Born shells you may redirect standard error and standard output separately. The standard error is labeled 2 and standard output is labeled 1. The phrase 2>& says to direct standard error into the same path as standard output. To pipe both standard error and standard output when using the Korn shell,

$ cc myprog.c 2>& | more Pipe both stderr and stdout in ksh.

The same trick works when redirecting into a file:

$ cc myprog.c 2>& > err.file Redirecting stderr in ksh.

If you want to direct the standard output and standard error to different locations, it becomes complicated in the C shell:

% (cc myprog.c > output) >& err.file Stderr & stdout to different files.

Here we have directed standard output to the file output. While it looks like we have also redirected both the standard output and the standard error to the file err.file because the standard output already has been redirected, we just get the standard error in the error file. In the Korn shell the redirection is simpler since we may direct standard output and standard error separately:

$ cc myprog.c 2> err.file > output Redirecting stderr in ksh.



next up previous contents index
Next: WORKSTATION SETUP AND Up: Redirecting I/O and Previous: Combining I/O Redirection