27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 29. Of Zeros and Nulls<br />

/dev/zero and /dev/null<br />

Uses of /dev/null<br />

Think of /dev/null as a "black hole". It is the nearest equivalent to a write−only file. Everything<br />

written to it disappears forever. Attempts to read or output from it result in nothing. Nevertheless,<br />

/dev/null can be quite useful from both the command line and in scripts.<br />

Suppressing stdout.<br />

cat $filename >/dev/null<br />

# Contents of the file will not list to stdout.<br />

Suppressing stderr (from Example 12−2).<br />

rm $badname 2>/dev/null<br />

# So error messages [stderr] deep−sixed.<br />

Suppressing output from both stdout and stderr.<br />

cat $filename 2>/dev/null >/dev/null<br />

# If "$filename" does not exist, there will be no error message output.<br />

# If "$filename" does exist, the contents of the file will not list to stdout.<br />

# Therefore, no output at all will result from the above line of code.<br />

#<br />

# This can be useful in situations where the return code from a command<br />

#+ needs to be tested, but no output is desired.<br />

#<br />

# cat $filename &>/dev/null<br />

# also works, as Baris Cicek points out.<br />

Deleting contents of a file, but preserving the file itself, with all attendant permissions (from Example<br />

2−1 and Example 2−2):<br />

cat /dev/null > /var/log/messages<br />

# : > /var/log/messages has same effect, but does not spawn a new process.<br />

cat /dev/null > /var/log/wtmp<br />

Automatically emptying the contents of a logfile (especially good for dealing with those nasty<br />

"cookies" sent by Web commercial sites):<br />

Example 29−1. Hiding the cookie jar<br />

if [ −f ~/.netscape/cookies ] # Remove, if exists.<br />

then<br />

rm −f ~/.netscape/cookies<br />

fi<br />

ln −s /dev/null ~/.netscape/cookies<br />

Chapter 29. Of Zeros and Nulls 316

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!