The ‘/dev‘ directory in Linux and Unix based systems contains files corresponding to devices attached to the system. For example, as seen in the screenshot below, the CD drive is accessed using ‘cdrom‘, DVD drive with ‘dvd‘, hard drives are accessed using ‘sda1‘, ‘sda2‘, etc.
All these files communicate with the Linux system through the respective files in ‘/dev‘. The input/output processing of the devices takes place through these files. This is due to an important feature of the filesystem in Linux: everything is either a file or a directory.
$ cd /dev
Apart from these files which represent actual physical devices, there are some files in ‘/dev‘ which are known as ‘virtual device files‘ or ‘pseudo-device files‘. These files do not handle any devices and they are used for providing various functions required by the operating system.
For example, the file ‘/dev/random‘ when read, returns a set of random bytes generated by the random number generator.
One such file which is very popularly used is ‘/dev/null‘. Today we’ll try to learn about this file and for what purpose it is present in Linux.
/dev/null: What is it, and Why is it there?
In Linux, you might know that primarily the command line is used to run not only administrative processes or server management processes but also day to day processes. The command line (also called the Terminal) executes a program and prints the output (also known as log).
Two types of output are printed by the terminal:
- STDOUT, or ‘Standard Output’ is the output containing general information about the program run and success messages of the program run.
- STDERR, or ‘Standard Error‘ is the output containing error messages of the program run.
The larger the process, the larger is the log produced by the process. Many times, most of the log is not even relevant for the user. This even utilizes unnecessary resources of the machine.
In such cases, ‘/dev/null‘ comes in handy. This file is used as a ‘sink‘, i.e. a target file to write the log. Except that as soon as the log is written to this file, it is immediately discarded/deleted by the operating system.
$ ls /dev
Highlighted in yellow above is the file ‘null‘ in the directory ‘dev‘ filesystem.
Thus, due to the data being discarded immediately, unnecessary memory consumption is prevented. This is especially useful in the case of complex automation scripts that contain the output of 10s and 20s of programs.
To direct the output of any program to /dev/null, simply use the redirection operator in the Linux shell
(‘>’) as follows.
$ ls > /dev/null
As you can see, when ‘ls‘ is run normally it displays the contents of the directory as output, however, when it is redirected to /dev/null, the complete output is suppressed.
In this article, we learned about /dev/null and its use in Linux. You can learn more about redirecting output to /dev/null with various combinations of STDOUT and STDERR here.
If you have any questions or feedback, let us know in the comments below!