Think of /dev/null as a "black hole". It is the nearest equivalent to a write-only file. Everything written to it disappears forever. Attempts to read or output from it result in nothing. Nevertheless, /dev/null can be quite useful from both the command line and in scripts.
Suppressing stdout or stderr (from Example 12-2):
rm $badname 2>/dev/null # So error messages [stderr] deep-sixed. |
Deleting contents of a file, but preserving the file itself, with all attendant permissions (from Example 2-1 and Example 2-2):
cat /dev/null > /var/log/messages # : > /var/log/messages has same effect, but does not spawn a new process. cat /dev/null > /var/log/wtmp |
Automatically emptying the contents of a log file (especially good for dealing with those nasty "cookies" sent by Web commercial sites):
Like /dev/null, /dev/zero is a pseudo file, but it actually contains nulls (numerical zeros, not the ASCII kind). Output written to it disappears, and it is fairly difficult to actually read the nulls in /dev/zero, though it can be done with od or a hex editor. The chief use for /dev/zero is in creating an initialized dummy file of specified length intended as a temporary swap file.
Example 29-2. Setting up a swapfile using /dev/zero
#!/bin/bash # Creating a swapfile. # This script must be run as root. ROOT_UID=0 # Root has $UID 0. E_WRONG_USER=65 # Not root? FILE=/swap BLOCKSIZE=1024 MINBLOCKS=40 SUCCESS=0 if [ "$UID" -ne "$ROOT_UID" ] then echo; echo "You must be root to run this script."; echo exit $E_WRONG_USER fi if [ -n "$1" ] then blocks=$1 else blocks=$MINBLOCKS # Set to default of 40 blocks fi # if nothing specified on command line. if [ "$blocks" -lt $MINBLOCKS ] then blocks=$MINBLOCKS # Must be at least 40 blocks long. fi echo "Creating swap file of size $blocks blocks (KB)." dd if=/dev/zero of=$FILE bs=$BLOCKSIZE count=$blocks # Zero out file. mkswap $FILE $blocks # Designate it a swap file. swapon $FILE # Activate swap file. echo "Swap file created and activated." exit $SUCCESS |
Another application of /dev/zero is to "zero out" a file of a designated size for a special purpose, such as mounting a filesystem on a loopback device (see Example 13-6) or securely deleting a file (see Example 12-30).