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:

get_logfile () {
    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
  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
source $RUN/shell_common.sh

And end the script with:

#script ends here

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"


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