Search code examples
linuxbashwaitkilltail

Tail a log into an excerpt in real time


I have a process I am running whereby I need to capture the logs from a daemon for the duration the process is running. I have a solution I've cobbled together, but I was hoping someone could point me at a slightly more elegant way to do it. The specific thing that's irking me is that, because I'm using set -e to alert me to any problems, kill generates an error from tail which I have to eat with || :, which to me is an ugly hack.

#!/bin/bash
set -e
LOGDIR="/path/to/logs"
LOCKFILE="/path/to/lockfile"
NOW=$( date +'%Y-%m-%d-%H%M' )

bail() {
   echo "$(hostname) $(pwd) error in line $1 of THING" | mail -s "Error: THING on $(hostname) line# $1" me@example.com
}

if [ -f $LOCKFILE ] ; then
   echo "$(hostname) $(pwd) ${0} is locked $(ls -l ${LOCKFILE})"| mail -s "LOCKED: THING" me@example.com
   exit
else
   trap "rm -f $LOCKFILE" EXIT
   trap 'bail $LINENO' ERR
fi

echo $$ > $LOCKFILE
/bin/date >> $LOCKFILE

tail -f path/to/daemon/logfile > $LOGDIR/${NOW}-THING.log &
TAILPID=$!

sleep 1
/path/to/monitored-process
sleep 1 # Allow for last couple log entries to flush
kill $TAILPID
wait $TAILPID || : # Need the no-op to eat the expected error from `kill`ing tail

/bin/rm -f $LOCKFILE

Solution

  • In my opinion, what you have is quite elegant.

    As a solution, how about putting set +e just before the kill, and set -e after? Since you are expecting the error status when tail is killed, don't look for it.