In Linux, the β/dev/nullβ is a special file that discards all data written to it. It acts as a black hole for data and is often used to discard unwanted output from commands or to make a file appear by moving it to /dev/null. Its purpose is to provide a location for data to be discarded.
This tutorial will illustrate the β/dev/nullβ and different examples.
- What is dev/null in Linux?
- Discarding Unwanted Output
- Suppressing Error Messages
- Making a File Disappear
- Discard Ping Output to the Server Address
How to Use /dev/null/ in Linux?
The administrators utilize the β/dev/nullβ file to discard unwanted output, suppress error messages, or void any commandβs output. This section explains the usage of β/dev/nullβ in Linux.
Example 1: Discarding Unwanted Output
An example is carried out to discard the unwanted output without displaying it in the terminal. For instance, the βlsβ command displays the contents of the “/tmp” directory. Instead of printing the output on the screen, it redirects it to /dev/null and discards it:
$ ls -l /tmp > /dev/null
The output confirms that the contents of the “/tmp” directory have been discarded.
Example 2: Suppressing Error Messages
An example is considered in which the “grep” command searches for a pattern “some_pattern” in the non-existent file as “/non_existent_file“. Because the file does not exist, an error message will be generated, but it will be redirected to β/dev/nullβ and discarded, making it silent. The β2β is the reference to the standard error(output stream) that redirects output:
$ grep 'some_pattern' /non_existent_file 2> /dev/null
The output suppresses the error message.
Example 3: Making a File Disappear
To make a file disappear, users can move to the β/dev/nullβ directory by discarding its contents. For example, the command “mv” moves the file “file2.txt” to β/dev/nullβ and makes its contents inaccessible:
$ sudo mv file2.txt /dev/null
The output confirms that βfile2.txtβ has disappeared from the home directory.
Example 4: Discard Ping Output to the Server Address
The βpingβ command continuously pings to the server address which users specified. The β/dev/null 2>&1β command is utilized to discard the output of the βpingβ command by specifying the βgoogle.comβ address. The β2>&1β redirect the standard error stream to standard output:
$ ping google.com >/dev/null 2>&1
The output confirms that ping to the βgoogle.comβ has been discarded.
Conclusion
The β/dev/nullβ is a powerful tool in Linux that allows users to discard unwanted data, suppress error messages, and make files disappear. Users must care that the data will not be retrieved after sending it to the β/dev/nullβ directory. This article briefly explained the β/dev/nullβ and the possible examples.