/dev/null is also part of the beauty of Unix's I/O "redirection" feature, which lets you mix and match how you want input and output from your programs handled.
When a process runs, it can read from many sources and write to many destinations. By convention three are commonly used, called standard input (stdin), standard output (stdout), and standard error (stderr). Using shell conventions, you can send each of stdin, stdout, and stderr to your screen (the stuff you see in the Terminal window), attach them to particular disk files, use /dev/null (to make the input null or to toss output), attach them to a physical device (like a tape drive), or connect them to another process (which is called piping).
For example, this single shell command
can be used to display the word
hello on the screen, store it in a file, make it disappear, send it to a tape drive, or send it to a command named lp that prints it:
Code:
echo "hello"
echo "hello" >/Users/DoctorQ/Documents/hello.txt
echo "hello" >/dev/null
echo "hello" >/dev/mt0
echo "hello" | lp
and the
echo command itself doesn't have to know or care where the output is going.
In this case, the /dev/null choice wasn't very useful, but /dev/null is handy for commands that generate output you don't want this particular time, including cron tasks and the example
savar gave. I sometimes redirect the output of the
rm command (which removes a file) to /dev/null so I don't see an error message if the file doesn't exist. But other times I do want to see that message because it's a sign of a problem if the file doesn't exist, in which case I don't use /dev/null.
Code:
rm myfile.txt (error message displayed if file doesn't exist)
rm myfile.txt >/dev/null (no message displayed)
Note: I've purposely avoided mentioning differences among shells in the redirection syntax.