Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does cmd > /dev/null 2>&1 work?

I'm reading up on redirecting data to /dev/null and so I tried a simple test:

ping a.b.c  # which results in an address not found

If I try this:

ping a.b.c > /dev/null # prints the same error message as the one above

However, if I do this:

ping a.b.c > /dev/null 2>&1 # The error message is gone

That last solution is the desired solution, but what is happening with this 2>&1? My research so far suggest that 2 represents stderr and 1 represents stdout. So if I read it that way, it looks like I'm creating a stderr file and redirecting stdout to it?

If that is the case, what does the & in that command do?

like image 339
hax0r_n_code Avatar asked Jun 08 '13 02:06

hax0r_n_code


1 Answers

You are right, 2 is STDERR, 1 is STDOUT. When you do 2>&1 you are saying: "print to STDOUT (1) the things that would go to STDERR (2)". And before that, you said your STDOUT would go to /dev/null. Therefore, nothing is seen. In the examples 1 and 2 you get the output message because it is being printed to STDERR, as a regular redirection only redirects STDOUT.

And when you do the redirection, you are not creating a STDERR, the processes always have a STDERR and a STDOUT when they are created.

like image 138
msb Avatar answered Oct 01 '22 06:10

msb