2

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.

CyberMuz
  • 335
  • 1
  • 2
  • 8

1 Answers1

4

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
NZD
  • 246
  • 2
  • 4
  • 3
    Thank you, I will probably use something like this. I will probably modify the script so that instead of killing the tail process it creates the simlink to new to the most recent log file. Then I can tail -F the simlink. – CyberMuz Feb 26 '17 at 17:28