Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting | ||
---|---|---|
Prev | Chapter 16. I/O Redirection | Next |
Clever use of I/O redirection permits parsing and stitching together snippets of command output (see Example 11-6). This permits generating report and log files.
Example 16-12. Logging events
1 #!/bin/bash 2 # logevents.sh, by Stephane Chazelas. 3 4 # Event logging to a file. 5 # Must be run as root (for write access in /var/log). 6 7 ROOT_UID=0 # Only users with $UID 0 have root privileges. 8 E_NOTROOT=67 # Non-root exit error. 9 10 11 if [ "$UID" -ne "$ROOT_UID" ] 12 then 13 echo "Must be root to run this script." 14 exit $E_NOTROOT 15 fi 16 17 18 FD_DEBUG1=3 19 FD_DEBUG2=4 20 FD_DEBUG3=5 21 22 # Uncomment one of the two lines below to activate script. 23 # LOG_EVENTS=1 24 # LOG_VARS=1 25 26 27 log() # Writes time and date to log file. 28 { 29 echo "$(date) $*" >&7 # This *appends* the date to the file. 30 # See below. 31 } 32 33 34 35 case $LOG_LEVEL in 36 1) exec 3>&2 4> /dev/null 5> /dev/null;; 37 2) exec 3>&2 4>&2 5> /dev/null;; 38 3) exec 3>&2 4>&2 5>&2;; 39 *) exec 3> /dev/null 4> /dev/null 5> /dev/null;; 40 esac 41 42 FD_LOGVARS=6 43 if [[ $LOG_VARS ]] 44 then exec 6>> /var/log/vars.log 45 else exec 6> /dev/null # Bury output. 46 fi 47 48 FD_LOGEVENTS=7 49 if [[ $LOG_EVENTS ]] 50 then 51 # then exec 7 >(exec gawk '{print strftime(), $0}' >> /var/log/event.log) 52 # Above line will not work in Bash, version 2.04. 53 exec 7>> /var/log/event.log # Append to "event.log". 54 log # Write time and date. 55 else exec 7> /dev/null # Bury output. 56 fi 57 58 echo "DEBUG3: beginning" >&${FD_DEBUG3} 59 60 ls -l >&5 2>&4 # command1 >&5 2>&4 61 62 echo "Done" # command2 63 64 echo "sending mail" >&${FD_LOGEVENTS} # Writes "sending mail" to fd #7. 65 66 67 exit 0 |