3

Sometimes I am running a less +F on a log file, which I then truncate. I would like less to realize that the file has been truncated and start following the file as it is now. Currently, I am forced to do the following:

  1. (terminal 1) > less +F my-file.txt
  2. (terminal 2) > printf "" > my-file.txt
  3. (terminal 1) > quit less
  4. (terminal 1) > restart less: less +F my-file.txt

And I have to do steps 3-4 every time that I truncate the file (which is dozens o times a day). This is really a pain.

I would like to do:

  1. (terminal 1) > less +F my-file.txt (and whatever extra option is needed)
  2. (terminal 2) > printf "" > my-file.txt

And that's it. less would be automatically aware that the file has been truncated, and start following the new file from the beginning.

Is this possible? What flag should I use for less to achieve this?

blueFast
  • 4,000
  • 13
  • 36
  • 51

3 Answers3

1

Not precisely the answer you were looking for, but you could try using 'tail -F' (As opposed to 'tail -f') which will give you exactly the behavior you're looking for.

katriel
  • 4,407
  • 22
  • 20
  • Thanks, but tail is very limited compared to less. I want to use less, but I also want this tail feature. – blueFast May 02 '13 at 11:39
0

Why don't you combine them like so?

tail -F filename | tee | less

This works well for me.

Tim Lamballais
  • 136
  • 1
  • 6
0

You want to specify the --follow-name argument to less. From the man page:

Normally, if the input file is renamed while an F command is executing, less will continue to display the contents of the original file despite its name change. If --follow-name is specified, during an F command less will periodically attempt to reopen the file by name. If the reopen succeeds and the file is a different file from the original (which means that a new file has been created with the same name as the original (now renamed) file), less will display the contents of that new file.

So your steps would now be:

  1. (terminal 1) > less --follow-name +F my-file.txt
  2. (terminal 2) > printf "" > my-file.txt
  3. (terminal 1) > enjoy!

P.S. Instead of using printf, lots of shells will truncate with just the redirection operator: > my-file.txt

bonsaiviking
  • 4,355
  • 16
  • 26