How to Pipe standard error (STDERR) to another program
Thursday, January 24th, 2008Everybody 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


