Tuesday, July 12, 2005

Writing to nothing in UNIX

Ever used this before -
$ grep hello hi 2>/dev/null

Probably you have - or something similar to the one above. We are writing errors to what constitues in Unix to "nothing" or "null". What are we doing that for?!

Before we answer the above question, lets assume you have a file hello.txt, which contains a few lines of text. Run this command at the command line -
$ grep "test" hello.*

The output would be something like -
This is a good day and I love testing my code.

How do I find out which filename this is in? With grep, if the filename pattern matches only one file. it never writes the filename to the output. So then, how do we get the filename?
Simple! Try running this at the command line -
$ grep "test" hello.* /dev/null

Howzatt?! You provide a filename here where you are sure nothing can be found, because anything cannot be found in nothing!

So, coming back to the earlier question, what use is it to redirect output to a null file? Sometimes, you need a program to just execute without bugging you with its results. There are other instances where you might not need any errors to be logged (as in the first command). /dev/null could also be used to prevent some logs from being written, when you do not have any access to the source code which is writing the logs. Just create a symbolic link to this file and make it point to /dev/nul -
$ ln -s /dev/null mylog

So, what is the /dev/zero file?