Bash – Continuously tailing a rotating log file with date and time in filename

bashcommandlog-filestail

I have a log file in format log_name_YY-MM-DD_HH_mm.log. The log rotates every couple of hours and the new log is created containing the date and time of it's creation. Sometimes I need to tail the live output of this log with the tail -f command. After the log is rotated tail still points to old filename and must be manually restarted with the new filename.

Is there a way to automatically switch tail -f to use the new file? The tail -F option (tail --follow=name --retry) doesn't work in this case because the filename of the log changes.

Best Answer

You can create a script to tail the most recent log file in the background and then check regularly for a new log file. If there is a new log file, kill the old process and start tailing the new file.

Something like:

#!/bin/bash

PATTERN='log_name_??-??-??_??_??.log'

CURRENT=any_pattern # dummy pattern to start off first tail -f

while true; do
   NEWLOG=`ls -t $PATTERN|head -n1`
   if [[ $NEWLOG != $CURRENT ]]
   then
      kill $TAILPID 2>/dev/null
      CURRENT=$NEWLOG
      tail -f $CURRENT &
      TAILPID=$!
   fi
   sleep 1 # check regularly
done
Related Topic