Friday, 13 May 2011

> /dev/null 2>&1

What does "> /dev/null 2>&1" mean?

Ever wondered what the trailing garbage in some commands on a Unix system mean?  What's the funny looking  greater-than, ampersands and numbers after the commands mean? In this article we’ll explain those weird commands.
Here’s an example command:
mycommand > /dev/null 2>&1
Below is a graphical representation of whats going on.  This is explained later.


Output redirection

The greater-thans (>) in commands like these, redirect the program’s output somewhere. In this case, something is being redirected into /dev/null (which is a place you can dump anything you don’t want (often called the bit-bucket), and something is being redirected into &1 (meaning send to wherever STDOUT is going, explained further on).

Standard in, out, and error

There are three standard sources of input and output for a program. Standard input usually comes from the keyboard if it’s an interactive program, or from another program if it’s processing the other program’s output. The program usually prints to standard output, and sometimes prints to standard error. These three file descriptors (you can think of them as “data pipes”) are often called STDIN, STDOUT, and STDERR.
Sometimes they’re not named, they’re numbered! The built-in numberings for them are 0 for STDIN, 1 for STDOUT, and 2 for STDERR. By default, if you don’t name or number one explicitly, you’re talking about STDOUT.

Given that context, you can see the command above is redirecting standard output into /dev/null, then redirecting standard error into standard output (you have to put an & in front of the destination when you do this).
Note: You can redirect standard output or standard error to any file you choose, doesn't have to be /dev/null.
The short explanation, therefore, is “all output from this command should be shoved into a black hole.” That’s one good way to make a program be really quiet!

I put this page together a few years back on an internal Wiki in work. I don't remember where the images came from. I think our web designer did them up for me based on a few sketches I gave him.  Some of the content is from various other sites, but I figure, it's all about educating the "users", right?

2 comments:

  1. The images didn't come out for me, for some reason...I always thought there should have been a nice UI way to draw Unix style pipelines/redirections, particularly on the Amiga...

    ReplyDelete
  2. Eamon Harbison13 May 2011 at 18:57

    Dave, The images should be visible now.Cheers,Eamon.

    ReplyDelete