Ubuntu – I can read from /dev/null; how to fix it


I read the Wikipedia article on /dev/null and was playing around by moving files to /dev/null.

For this I created a test_file and put some contents in it:

$ touch test_file
$ echo "This is written by Aditya" > test_file
$ cat test_file
This is written by Aditya

Thereafter I tried to move the file to /dev/null:

$ mv test_file /dev/null
mv: inter-device move failed: ‘test_file’ to ‘/dev/null’; unable to remove target: Permission denied

Since, this gave me a Permission denied Error; I went ahead and used sudo as I normally do whenever I encounter a Permission denied error.

$ sudo mv test_file /dev/null

The command succeeded and test_file is no longer present in the directory.

However, the Wikipedia article says that it is not possible to recover anything moved to /dev/null and it gives an EOF to any process that tries to read from it. But, I can read from /dev/null:

$ cat /dev/null
This is written by Aditya

What did I do wrong and how do I fix /dev/null back to normal? And why did I encounter Permission denied error in the first place?

Best Answer

/dev/null is a file. A special file. A device file like /dev/sda or /dev/tty that talks to a piece of hardware on your system.

The only difference with /dev/null is that no hardware is linked to it. Any data you send to it is silently discarded. Like the following command:

echo "Hello World" > /dev/null

which won't print anything on your terminal because you send the output of echo to null, to the void, a black hole thus.

But when you did mv test_file /dev/null you've replaced the special file /dev/null by a normal text file, holding a copy of the content of your test_file. In other words, you've lost your /dev/null.

Now, what you have to do is (to reconstruct it):

sudo rm /dev/null
sudo mknod -m 0666 /dev/null c 1 3

You should reconstruct it because a lot of scripts by default send output to /dev/null. If /dev/null is no more a black hole but a regular text file, it may grow, grow and fill your file-system up. And I'm sure you want to avoid this.

And much more dangerous, a lot of scripts assume that reading from /dev/null will read nothing; breaking this assumption can lead to random garbage written in files all around your system... practically impossible to fix up.

And remember that Linux is multi-tasking: while you are playing with /dev/null, a lot of processes are running and can wreak havoc even during a few seconds "window of opportunity".

If you want to play with /dev/null you can create a copy and experiment with it:

sudo mknod -m 0666 /tmp/null c 1 3 

Will create a /tmp/null file that works in the exactly same way of /dev/null but that you can manipulate and test without any risk for your system.

Related Question