19.3. Applications

Clever use of I/O redirection permits parsing and stitching together snippets of command output (see Example 14-7). This permits generating report and log files.


Example 19-12. Logging events

   1 #!/bin/bash
   2 # logevents.sh
   3 # Author: Stephane Chazelas.
   4 # Used in ABS Guide with permission.
   5 
   6 # Event logging to a file.
   7 # Must be run as root (for write access in /var/log).
   8 
   9 ROOT_UID=0     # Only users with $UID 0 have root privileges.
  10 E_NOTROOT=67   # Non-root exit error.
  11 
  12 
  13 if [ "$UID" -ne "$ROOT_UID" ]
  14 then
  15   echo "Must be root to run this script."
  16   exit $E_NOTROOT
  17 fi  
  18 
  19 
  20 FD_DEBUG1=3
  21 FD_DEBUG2=4
  22 FD_DEBUG3=5
  23 
  24 # === Uncomment one of the two lines below to activate script. ===
  25 # LOG_EVENTS=1
  26 # LOG_VARS=1
  27 
  28 
  29 log()  # Writes time and date to log file.
  30 {
  31 echo "$(date)  $*" >&7     # This *appends* the date to the file.
  32 #     






  command substitution
  33                            # See below.
  34 }
  35 
  36 
  37 
  38 case $LOG_LEVEL in
  39  1) exec 3>&2         4> /dev/null 5> /dev/null;;
  40  2) exec 3>&2         4>&2         5> /dev/null;;
  41  3) exec 3>&2         4>&2         5>&2;;
  42  *) exec 3> /dev/null 4> /dev/null 5> /dev/null;;
  43 esac
  44 
  45 FD_LOGVARS=6
  46 if [[ $LOG_VARS ]]
  47 then exec 6>> /var/log/vars.log
  48 else exec 6> /dev/null                     # Bury output.
  49 fi
  50 
  51 FD_LOGEVENTS=7
  52 if [[ $LOG_EVENTS ]]
  53 then
  54   # exec 7 >(exec gawk '{print strftime(), $0}' >> /var/log/event.log)
  55   # Above line fails in versions of Bash more recent than 2.04. Why?
  56   exec 7>> /var/log/event.log              # Append to "event.log".
  57   log                                      # Write time and date.
  58 else exec 7> /dev/null                     # Bury output.
  59 fi
  60 
  61 echo "DEBUG3: beginning" >&${FD_DEBUG3}
  62 
  63 ls -l >&5 2>&4                             # command1 >&5 2>&4
  64 
  65 echo "Done"                                # command2 
  66 
  67 echo "sending mail" >&${FD_LOGEVENTS}
  68 # Writes "sending mail" to file descriptor #7.
  69 
  70 
  71 exit 0