In the /dev/null Zone

August 13, 2009

If you have read the comment from my post On my first Script, it was suggested that I use nohup firefox >& /dev/null & to solve my infinite loop problem.  Well I read up on the parts of this command and it seems that it should work (I have yet to try it, but should get around to it this weekend).  So it’s time to break it down for those of you who have never seen anything like this before.

Firstly, nohup allows a program to continue to run in the background even if the user logs out (or the terminal is closed).  However, this can cause ‘hanging’.  From what I understand this happens when your program produces some kind of output (standard or error) and you try to close the terminal (or log out I suppose).  But you are unable to because the system is still “working”.  Say you have a program called count which counts to 1,000,000,000.  Needless to say this will take a while and you would want to do other things while waiting for it to finish.  So you run nohup count, but you forget that count prints the numbers to standard output (the screen). Thus when you try to close the terminal you are unable to do so (whoops).

This is where /dev/null comes to the rescue (well partially, but we will get to that later).  /dev/null is basically a file that you can write to but not read, and anything written to it is automatically discarded (aka deleted or destroyed). Thus you could enter nohup count > /dev/null, so now all your numbers will be written to /dev/null and not the screen.

Now this is where things get a little “complicated”, but bear with me.  There are 3 differnet standard I/O streams.  STDIN (used for input, usually the keyboard), STDOUT (standard output to the screen), and STDERR (standard error).  By default the streams are numberd 0, 1, 2 repectively.  So the command 2>&1 will redirect standard error to standard output.  How is this useful at all you ask. Well here’s how.  nohup count > /dev/null 2>&1. The first part as you already know will redirect our output to /dev/null, but the second part makes sure that if there is any standard error that it will be redirected to standard output which is being directed to /dev/null (also knowns as the black hole).  Thus, we can finally let count run and be able to close the terminal with no worries.

I know this might have been a little lengthy, but it is a lot to cover.  I am sure there are things that I left out but the basics are there.