What are /dev/zero and /dev/null files in Linux

“/dev/zero” and “/dev/null” are two dummy device files that are useful for creating empty files. But there is a distinct difference in what they actually do. In this post, we will see the difference between the two and where they can be used.

/dev/zero file

It is used to create a file with no data but with the required size (A file with all zero’s written on it).

Let’s create file with /dev/zero:

# dd if=/dev/zero of=/opt/zero.txt bs=2048 count=2048
2048+0 records in
2048+0 records out
4194304 bytes (4.2 MB) copied, 0.150465 s, 27.9 MB/s

It creates a file that has continuous zeros in it. So we can say that /dev/zero is a file that is used to create a new file with some required size without any meaning to the data.

You can also use the /dev/zero file in conjuction with dd command to wipe out a disk. For example:

# dd if=/dev/zero of=/dev/sda bs=2K conv=noerror,sync

Another file that can be used in this process as well is/dev/null:

/dev/null

While sending all output is often a nice thing to do, another thing you will find yourself doing on a regular basis is redirecting errors (which you expect on some commands) to a special device: /dev/null.

The null kind of gives away the functionality: it’s somewhere between a trash can and a black hole. This file is even helpful in creating files with zero size.

For example, if you see I have few files and folders in current directory:

# ls
anaconda-ks.cfg  Documents  initial-setup-ks.cfg  Pictures  Templates
Desktop          Downloads  Music                 Public    Videos

If I redirect “ls” command output to “/dev/null” file, the output data can’t be retrive again even after reading null file:

# ls > /dev/null
# cat /dev/null
#

How To Recreate /dev/null

The commands below were placed in one line and separated by a semicolon ‘;’ to run as quickly and have a little effect on the running system as possible.

# rm /dev/null ; mknod -m 0666 /dev/null c 1 3 ;

Execute: yes

Verify that everything is fine and in place:

# ls -al /dev/null

Summary

When we redirect output to /dev/zero, it does precisely the same as /dev/null: the data disappears. However, in practice, /dev/null is most often used for this purpose.

So, why have this special device then? Because /dev/zero can also be used to read null bytes. Out of all possible 256 bytes, the null byte is the first: the hexadecimal 00. A null byte is often used to signify the termination of command.

Related Post