Skip to content

How to Pipe standard error (STDERR) to another program

Everybody who has a little knowledge in linux shell know about piping and redirection. Piping is done by ‘|’ sign and for redirection ‘>’, ‘<’, ‘<<’, ‘>>’, ‘<<<’ signs are used.To redirect standard output of a program to a file we use

% foo > bar.txt

or
% foo 1> bar.txt

To redirect standard error of a program to a file we use

% foo 2> bar.txt

The pipe command is used normally to pass one commands output to another programs input. To pass output of `foo` to `bar` we use

% foo | bar

The problem is `bar` always gets the standard output of `foo`. Not standard error.

I was trying like redirection.

% foo 2| bar

But this didn’t work. After some trial and error I found a way.

See the command bellow.

% foo 2>&1 1>/dev/null | bar

The extra part here is “2>&1 1>/dev/null“. What does it do? How does it work?

Well, `bar` takes output of `foo` not error. Keeping this in mind if I could redirect the standard error to standard output of `foo`, `bar` will get what it wants. But if I just redirect stderr to stdout, stdout will contain both original stdout content and new stderr content. To overcome this, I removed the original content of stdout at first then I do redirection.

1>/dev/null cleans the original content of standard output, then

2>&1 redirects standard error to standard output.

When `bar` is executed it has the input.



© 2008 by A K M Mokaddim

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

{ 3 } Comments

  1. Jerry Jeremiah | January 7, 2010 at 2:46 pm | Permalink

    This doesn’t work with ksh – at least not with the version of ksh on my box. The stderr gets merged with stdout and then that stream is sent to /dev/null so there is no output.

  2. Shiplu | January 7, 2010 at 3:00 pm | Permalink

    @Jerry

    You can use,
    % foo 1>/dev/null 2>&1 | bar

    It seems the order of redirection is reverse in ksh

  3. Evan Carroll | January 18, 2010 at 11:25 pm | Permalink

    Alternatively, you can just use the /dev/stdout /dev/stderr symlinks:
    – switcheroo.
    `perl -E’say “foo”; die “bar”;’ 2>/dev/stdout 1>/dev/stderr`

Post a Comment

Your email is never published nor shared. Required fields are marked *