Redirecting stderr in csh
Asked Answered
W

2

19

I'm executing a program that dumps crash report into STDERR from where I have to filter some necessary information. The problem is that I'm unable to redirect STDERR to STDOUT and PIPE it with grep

command 2>&1 >/dev/null | grep "^[^-]" >& /tmp/fl

Getting error: Ambiguous output redirect.

Same command works under bash terminal. What should I change to make it work ?

Weatherford answered 14/8, 2015 at 13:8 Comment(1)
See this answer.Machinery
S
30

csh is significantly more limited than bash when it comes to file redirection. In csh, you can redirect stdout with the usual > operator, you can redirect both stdout and stderr with the >& operator, you can pipe stdout and stderr with the |& operator, but there is no single operator to redirect stderr alone.

The usual workaround is to execute the command in a sub-shell, redirecting stdout in that sub-shell to whatever file you want (/dev/null in this case), and then use the |& operator to redirect stdout and stderr of the sub-shell to the next command in the main shell.

In your case, this means something like:

( command >/dev/null ) |& grep "^[^-]" >&/tmp/fl

Because stdout is redirected to /dev/null inside the sub-shell, the |& operator will end up acting as 2>&1 in bash - since stdout is discarded in the sub-shell, nothing written to stdout will ever reach the pipe.

Savoury answered 14/8, 2015 at 14:12 Comment(2)
I thought the usual workaround was to invoke sh: sh -c "command 2>&1 > /dev/null"Kenzie
@WilliamPursell Yeah, sure. I assumed he wants to remain in csh for some reason.Thirza
E
8

If you dont mind mixing stdout and stderr into the pipe you can use

command |& grep "^[^-]" >& /tmp/fl

Otherwise you can do the hack:

(command >/dev/null) |& grep "^[^-]" >& /tmp/fl

which separates out stdout to null, then piping stdout and stderr just gives stderr as content.

Entopic answered 14/8, 2015 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.