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.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

16.3. Applications<br />

Clever use of I/O redirection permits parsing and stitching together snippets of command output (see Example<br />

11−6). This permits generating report and log files.<br />

Example 16−11. Logging events<br />

#!/bin/bash<br />

# logevents.sh, by Stephane Chazelas.<br />

# Event logging to a file.<br />

# Must be run as root (for write access in /var/log).<br />

ROOT_UID=0<br />

E_NOTROOT=67<br />

# Only users with $UID 0 have root privileges.<br />

# Non−root exit error.<br />

if [ "$UID" −ne "$ROOT_UID" ]<br />

then<br />

echo "Must be root to run this script."<br />

exit $E_NOTROOT<br />

fi<br />

FD_DEBUG1=3<br />

FD_DEBUG2=4<br />

FD_DEBUG3=5<br />

# Uncomment one of the two lines below to activate script.<br />

# LOG_EVENTS=1<br />

# LOG_VARS=1<br />

log() # Writes time and date to log file.<br />

{<br />

echo "$(date) $*" >&7 # This *appends* the date to the file.<br />

# See below.<br />

}<br />

case $LOG_LEVEL in<br />

1) exec 3>&2 4> /dev/null 5> /dev/null;;<br />

2) exec 3>&2 4>&2 5> /dev/null;;<br />

3) exec 3>&2 4>&2 5>&2;;<br />

*) exec 3> /dev/null 4> /dev/null 5> /dev/null;;<br />

esac<br />

FD_LOGVARS=6<br />

if [[ $LOG_VARS ]]<br />

then exec 6>> /var/log/vars.log<br />

else exec 6> /dev/null<br />

fi<br />

# Bury output.<br />

FD_LOGEVENTS=7<br />

if [[ $LOG_EVENTS ]]<br />

then<br />

Chapter 16. I/O Redirection 251

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

Saved successfully!

Ooh no, something went wrong!