How to monitor a file that fully recreates during its run

filesMySQLtail

This is a follow-up question of

Why are some file changes not shown in tail -f?

With the use of capital F: tail -F I can monitor the output of

tail -F ~/.mysql_history

from the manual:

--retry
      keep trying to open a file even if it is inaccessible when  tail
      starts  or if it becomes inaccessible later; useful when follow-
      ing by name, i.e., with --follow=name

-f, --follow[={name|descriptor}]
      output appended data as the file grows; -f, --follow, and --fol-
      low=descriptor are equivalent

-F     same as --follow=name --retry

but then the whole file is added to the output each time it changes.

Is there a way to tail the .mysql_history file correctly?

I also tried

tail --follow=name ~/.mysql_history 

but then I get the same behaviour and additionally this each time the history file changes:

tail: '.mysql_history' has been replaced; following end of new file

(using LC_ALL=C tail --follow=name ~/.mysql_history to get the english errormessage)

My end goal is to redirect the complete output of all changes in the mysql history into another file, but this is not satisfying:

tail -F ~/.mysql_history >> ~/.mysql_complete_history

Best Answer

You could try something like:

perl -e '
  $f = shift;
  while (open F, "<", $f) {
    seek F, $n, 0;
    while (<F>) {print};
    $n = tell F;
    sleep 1;
  }' ~/.mysql_history

tail -f reads the tail of the file and then sits there trying to read any new stuff every second. So does tail -F, but it also checks if the current file descriptor is still pointing to the same directory entry and starts with the new file if need be.

Here, we get it further. The idea being to reopen the file every second and seek in back to where we left it last time.

Related Question