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

{ 3 } Comments
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.
@Jerry
You can use,
% foo 1>/dev/null 2>&1 | bar
It seems the order of redirection is reverse in ksh
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