Last Updated: February 25, 2016
·
1.638K
· ashokisaac

BASH (very rudimentary) logging

Here's an extremely simple logging system for 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"

Note:

  • the logs are created under a 'logs/' directory.
  • each log file is a "daily" log matching script filename like so 'logs/myscript.YYYYMMDD.log'
  • Comments, refinements welcome :)

1 Response
Add your response

To get the log filename: $0 refers to the script name. Using parameter expansion ${v##/}
to remove everything starting from the front (left) until the last /, the greedy match essentially giving us the file name with extension. Then using the same, now from the trailing end (right) to remove the extension, i.e
${F%%.
}.

over 1 year ago ·