/dev/null is a pseudo-device file in Linux, which is used to discard output coming from programs, especially the ones executed on the command line. This file behaves like a sink, i.e. a target file which can be written, however as soon as any stream of data is written to this file, it is immediately deleted.
This is useful to get rid of the output that is not required by the user. Programs and processes can generate output logs of huge length, and it gets messy at times to analyze the log.
For example, sometimes there are two errors being thrown by a program, but the error logs are lost somewhere in between hundreds of information message logs. In such a case we can dump the information message logs to /dev/null.
In the above example, the error output by a program is called STDERR (Standard Error) in Linux and is represented by the integer ‘2’, while the success and information output is called STDOUT (Standard Output), and is represented by the integer ‘1’.
Now, you might have seen the following command line statement very often, which discards both STDERR and STDOUT to /dev/null.
$ command_name > /dev/null 2>&1
Let us try to understand what this means.
'>' is called a redirection operator. It redirects the output to the file specified after it, which in this case is /dev/null, instead of printing it on the terminal.
Does this mean ALL the output of the command is redirected to /dev/null with the
'>' operator? No. When used as shown above, the operator only redirects the STDOUT.
Hence, we have the last part of the command.
'2>&1' means: redirect STDERR (2) to STDOUT (1). The reason we have to specify ‘&1’ and not simply ‘1’ is that simply writing ‘1’ will redirect the output to a text file with the name ‘1’. With the ampersand
(&) the system recognizes that the 1 is not a filename, but the file descriptor STDOUT.
Thus, we redirect STDOUT to /dev/null and STDERR to STDOUT and in such a way, the complete output of the program(s) is discarded in /dev/null.
For example, executing mv command with and without ‘>/dev/null 2>&1’.
$ mv tmp.txt test/tmp2.txt /tmp
With redirection of STDOUT:
$ mv tmp.txt test/tmp2.txt /tmp > /dev/null
With redirection of STDOUT and STDERR:
$ mv tmp.txt test/tmp2.txt /tmp > /dev/null 2>&1
In this article, we tried to understand what is the meaning of the popularly used command phrase in Linux:
'> /dev/null 2>&1'. If you want to learn about ‘/dev/null‘ in more depth, you can do so here.
If you have any questions or comments, let us know in the comments below!