Tuesday Tiny Techie Tip

/dev/null

/dev/null is the proverbial bottomless pit. You can put an infinite amount of stuff into it and it will stay empty. It's magic.

/dev/null is a special file whose behavior is designed into the UNIX kernel. Any attempt to read from /dev/null returns an end-of-file indication. Writes to /dev/null quietly disappear. It's mostly useful for discarding output:


% ypcat passwd | grep jeffy > /dev/null

You would do this if you weren't interested in the information in the passwd database with my name on it, but only wanted to know if there was some. The return status of grep(1) indicates whether it found the pattern it was looking for, so the output can be discarded.

Here's a tricky way to do debugging statements in a Bourne shell script:


#!/bin/sh

if [ X$1 = Xdebug ]
then
    exec 3>&2
    echo "Debugging output is on" >&3
else
    exec 3>/dev/null
fi

echo "We be debugging now" >&3

In this script I'm using the usually unused fd3 for debugging output, and controlling whether debugging output is enabled by sending the word "debug" as the first argument to the script.

If the first argument to the script is the word "debug", output to fd3 gets sent to the same place as fd2 (that's what the "exec 3>&2" does, redirects fd3 to fd2 which is stderr).

If the word "debug" isn't there, then the "exec 3>/dev/null" causes all further output to fd3 to be sent to /dev/null where it disappears.

/dev/null is also useful for closing input:


% /usr/ucb/mail -s "important stuff" jeffy < /dev/null

This will send me email with the subject "important stuff" and an empty body.


Tuesday Tiny Techie Tip -- 22 April 1997
Forward to (04/29/97)
Back to (04/15/97)
Written by Jeff Youngstrom

Up to the TTTT index

Tuesday Tiny Techie Tips are all © Copyright 1996-1997 by Jeff Youngstrom. Please ask permission before reproducing any of this material.