1

My program outputs to stderr and stdout. I want to grep for "pattern" either in stderr and stdout. And I want the rest to be sent to /dev/null.

If I pipe after redirect stderr : ./prog 2>/dev/null | grep "pattern" I don't get the lines of stderr that contain "pattern".

If I pipe before redirecting stderr : ./prog | grep "pattern" 2>/dev/null none of stderr is redirected to /dev/null

thank you for your help.

4
  • If I pipe before redirecting stderr : ./prog | grep "pattern" 2>/dev/null none of stderr is redirected to /dev/null: and how is this bad? Commented Dec 18, 2013 at 10:46
  • I would like only the lines containing "pattern" to be visible. Not all of stderr.
    – Jav
    Commented Dec 18, 2013 at 11:11
  • This is what you get with /prog | grep "pattern" automatically. Commented Dec 18, 2013 at 11:19
  • @MariusMatutiae: no, an ordinary pipe ("|") only forwards stdout to the next process. stderr would pass "sideways" and show up completely (unfiltered) in the output.
    – dischoen
    Commented Dec 18, 2013 at 12:46

2 Answers 2

7

if you do not care whether the string match originates from stdout or stderr, then just merge the two streams by redirecting stderr to stdout, then do the grep:

$ your_program 2>&1 | grep "pattern"

the example works in sh, bash, ksh, zsh. csh should be:

$ your_program |& grep "pattern"
1
./prog 2>&1 | grep pattern

You must see only the lines containing "pattern"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .