Why is redirecting STDERR to /dev/null done this way?

This does not make sense to me.

wibble > /dev/null 2>&1

I think it would make more sense if it was something like this:

wibble 2>&1 > /dev/null

In other words

Commands Output Sendall STDERRORS to STDOUT then SEND it all to /dev/null

What is the thinking behind the order of the command redirection xxx > /dev/null 2>1?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The redirects are processed from left to right. If you do

2>&1 1> /dev/null

The first redirect makes stderr point to the stream that stdout points to at that time (which is your tty essentially). It doesn’t make stderr an alias of stdout.

Then stdout is redirected to the bit bucket. The stdout redirect doesn’t affect the previous stderr redirect. stderr still refers to your tty.

So:

ls file_that_doesnt_exist 2>&1 1> /dev/null

will print only the error message on your terminal.

The bash redirection documentation page mentions this explicitly:

Note that the order of redirections is significant. For example, the command

          ls > dirlist 2>&1

directs both standard output and standard error to the file dirlist, while the command

          ls 2>&1 > dirlist

directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x