June 1, 2014 · Linux ·

Logging for Shell scripts, simplified.

Some years ago I developed a set of scripts that I sell (and therefore install) on my client's webservers. Many of these scripts are long-running and do a lot of heavy-lifting, processing tens of thousands of database and file records.

I like to be able to log messages to file so I can track errors, or even just to be able to tell my client, "Here's exactly when this order was sent to the dropshipper".

Here's an extremely simple logging system I use for my BASH scripts:

#!/bin/sh
#shell_common.sh
get_logfile () {
    v="$1"
    F=${v##*/}
    LOG="$RUN/logs/${F%%.*}.`date +%Y%m%d`.log"
    echo $LOG
}

iplog () {
    echo "`date`" $1 | tee -a $logfile
}

ilog () {
    echo "`date` $1" >>  $logfile
}

script_init () {
  #Create a log file
  SCR=$0
  logfile=`get_logfile $SCR`

  #init message to log
  iplog "Script $SCR started, using LOG FILE: $logfile"
}

script_exit () {
   #exit message to log
  iplog "Script $SCR complete"
  ilog ""
 }   

The way I use this is, at the start of my scripts:

#Set the run directory
RUN=~/Scripts
source $RUN/shell_common.sh
script_init

And end the script with:

#script ends here
script_exit

When I need to write to log:

ilog "This message will be written to the log file"
iplog "This message will be written to sysout and log"

Notes:

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket