what is the meaning of /dev/null 2>&1

CharanR used Ask the Experts™

I see this in a lot of scripts
What exactly does this mean and what is the use of this?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2009
The /dev/null portion is the bitbucket. It is the null device in UNIX that output can be directed to to discard it.

That part is completely separate from the 2>&1

2>&1 is redirecting stderr (2) to the same file as stdout (1)

You could also say:

who > foo.txt 2>&1

Top Expert 2009

Also, your sample /dev/null is a fragment, normally you see a > before it:

> /dev/null
Top Expert 2009
I might not have explained it well.

The whole point of using

something > /dev/null

is to discard output for scripts that are "silent" and not expected to generate output.
   * 2 is the default file descriptor for stderr.
    * 1 is the default file descriptor for stdout.
    * >& is shell syntax for "fold a file descriptor into another"

1 is stdout. 2 is stderr.

Here is one way to remember this construct (altough it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows is a file descriptor and not a filename. So the construct becomes: 2>&1.
Monis MontherSystem Architect
To give some more explanation

 the  > sign means redirect to a file

The question is redirect what????, the answer is anything on the screen , instead of appearing on the screen it is saved to the file.

Another question might be , what is stdout and stderr.

Well not all what you see on the screen is considered output for example if you are at /etc

run the command

ls -l hosts fakefile

you will get the permissions for hosts and you will get the no such file or directory error message saying that there is no such file called fakfile

The system handles each message separately , the normal output is handled by a function in the system called stdout and the error message was handled by another functoin called stderr although both appear on your screen they are handled separately, now if you want to save out to a file you simply

command > file   this will save normal output, while

command 2> file this will save the error message to the file

sometimes you need to have the error messages redirected to the output handler so you do this

2 > &1 which means redirect all error messages to the output channel to be handled by stdout

Why is it written like this ??   check askb answer


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial