[ACCEPTED]-How can I redirect STDERR to STDOUT, but ignore the original STDOUT?-stdout

Accepted answer
Score: 114

What does not work:

The reason the last command you quoted:

cmd 1>/dev/null 2>&1 | grep pattern

does 48 not work, stems from a confusion on the 47 order in which redirection works. You expected 46 the last quoted redirection to be applied 45 to the ones before it on every output, so 44 that output the original standard output 43 file descriptor (1) will go to /dev/null, and 42 output to the standard error file descriptor 41 (2) will go to the original standard output.

However, this 40 is not how shell redirection works. Each 39 redirection causes the file descriptors 38 to be "remapped" by closing the 37 "source" and duplicating the "destination" into 36 it (see the man pages of dup(2) and close(2)), in order. This 35 means that in your command standard output 34 is first replaced with /dev/null, and then standard 33 error replaced with standard output, which 32 is /dev/null already.

What works:

Therefore, to obtain the desired 31 effect, you just need to reverse the redirections. Then 30 you will have standard error go to standard 29 output, and the original standard output 28 go to /dev/null:

cmd 2>&1 >/dev/null | grep pattern

(note that the 1 before > is unnecessary 27 - for output redirection standard output 26 is the default)

Addendum: Charlie mentioned redirecting 25 to &- to close a file descriptor. If using 24 an interactive shell which supports that 23 extension (bash and some other implementations 22 do but not all and it is not standard), you can also 21 do it like this:

cmd 2>&1 >&- | grep pattern

This may be better - it 20 can save some time, because when the command 19 tries to write to standard output the call 18 to write may fail immediately without waiting 17 for a context switch into the kernel and 16 the driver handling /dev/null (depending on the system 15 call implementation - some may catch this 14 in the libc function, and some may also have 13 special handling for /dev/null). If there is a lot 12 of output that can be worthwhile, and it's 11 faster to type.

This will mostly work because 10 most programs do not care if they fail to 9 write to standard output (who really checks 8 the return value of printf?) and will not mind 7 that standard output is closed. But some 6 programs can bail out with a failure code 5 if write fails - usually block processors, programs 4 using some careful library for I/O or logging 3 to stdandard output. So if it doesn't work 2 remember that this is a likely cause and 1 try /dev/null.

Score: 4

Close STDOUT first:

1>&-, >&-

See here.


More Related questions