In Linux, programs are very commonly accessed using the command line and the output, as such, is displayed on the terminal screen. The output consists of two parts: STDOUT (Standard Output), which contains information logs and success messages, and STDERR (Standard Error), which contains error messages.
Many times, the output contains a lot of information that is not relevant, and which unnecessarily utilizes system resources. In the case of complex automation scripts especially, where there are a lot of programs being run one after the other, the displayed log is huge.
In such cases, we can make use of the pseudo-device file ‘/dev/null‘ to redirect the output. When the output is redirected to /dev/null, it is immediately discarded, and thus, no resource utilization takes place.
Let’s see how to redirect output to /dev/null in Linux.
Let us take an example of the mv command trying to move two files to a particular directory, where one file is moved successfully (displays STDOUT) and the other gives an error while moving (displays STDERR).
$ mv -v tmp.c /etc/apt/sources.list /tmp
Note: The '-v'
argument to mv displays the success log when a file is moved. Without the flag, nothing is printed to STDOUT.
Now, to redirect only the STDOUT to /dev/null, i.e. to discard the standard output, use the following:
$ mv -v tmp.c /etc/apt/sources.list /tmp 1>/dev/null
What does ‘1>/dev/null’ mean?
Here '1'
indicates STDOUT, which is a standard integer assigned by Linux for the same. The operator '>'
, called a redirection operator, writes data to a file. The file specified in this case is /dev/null. Hence, the data is ultimately discarded.
If any other file were given instead of /dev/null, the standard output would have been written to that file.
Similarly, to redirect only the STDERR to /dev/null, use the integer '2'
instead of '1'
. The integer '2'
stands for standard error.
$ mv -v tmp.c /etc/apt/sources.list /tmp 2>/dev/null
As you can see, the standard error is not displayed on the terminal now as it is discarded in /dev/null.
Finally, to discard both STDOUT and STDERR at the same time, use the following:
$ mv -v tmp.c /etc/apt/sources.list /tmp &>/dev/null
The ampersand character ('&')
denotes that both the standard output and standard error has to be redirected to /dev/null and discarded. Hence, in the last screenshot, we do not see any output printed on the screen at all.
Conclusion
In this article, we have seen how to redirect output to /dev/null. The same can be used in either command or in complex Bash scripts which generate a heavy amount of log. In case if the script needs debugging, or has to be tested; in such cases, the log is required to view and analyze the errors properly.
However in cases when the output is already known and anticipated, it can be discarded with /dev/null. If you have any questions or feedback, let us know in the comments below!