Advanced Bash-Scripting HOWTO: A guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 3. Tutorial / Reference | Next |
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 3-98):
1 rm $badname 2>/dev/null 2 # 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):
1 cat /dev/null > /var/log/messages 2 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):
1 rm -f ~/.netscape/cookies 2 ln -s /dev/null ~/.netscape/cookies 3 # All cookies now get sent to a black hole, rather than saved to disk. |
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 3-97. Setting up a swapfile using /dev/zero
1 #!/bin/bash 2 3 # Creating a swapfile. 4 # This script must be run as root. 5 6 FILE=/swap 7 BLOCKSIZE=1024 8 PARAM_ERROR=33 9 SUCCESS=0 10 11 12 if [ -z $1 ] 13 then 14 echo "Usage: `basename $0` swapfile-size" 15 # Must be at least 40 blocks. 16 exit $PARAM_ERROR 17 fi 18 19 dd if=/dev/zero of=$FILE bs=$BLOCKSIZE count=$1 20 21 echo "Creating swapfile of size $1 blocks (KB)." 22 23 mkswap $FILE $1 24 swapon $FILE 25 26 echo "Swapfile activated." 27 28 exit $SUCCESS |