11

In less is there a command for reloading a file from disk, so that less will show any changes made to a file since less was started? This would saving me have to terminate and restart less if I want to see changes to the file I'm viewing.

3

3 Answers 3

7

There are two possibly relevant commands detailed in the fine manual for less(1)

   R      Repaint the screen, discarding any buffered  input.   Useful  if
          the file is changing while it is being viewed.

   F      Scroll  forward, and keep trying to read when the end of file is
          reached.  Normally this command would be used  when  already  at
          the  end of the file.  It is a way to monitor the tail of a file
          which is growing while it is being  viewed.   (The  behavior  is
          similar to the "tail -f" command.)
4

R for repaint does not always reload the file.[1]

A workaround that always reloads the file is to press hq, which will open the Help page, then quit. It has a side effect of forcing the file to reload.


[1] Here are some examples of situations that R do and do not reload:

  • > and >> changes: DO get reloaded
  • sed -i, gEdit, TextEdit: DO NOT get reloaded
  • On Linux, vi changes: DO get reloaded
  • On Mac, vi changes: DO NOT get reloaded

I believe the difference comes down to whether the inode changes (you can check with ls -i foo.txt). If the inode changes, then R will not work.

2
  • 1
    works for me on Mac. less --version gives less 487 (POSIX regular expressions) Apr 17, 2019 at 15:30
  • 2
    @johnsullivan Thanks for the comment. I revisited my answer and found that it depends on the situation. When using vi to edit on Mac, R doesn't work. But vi on Linux does. See my revised answer for more details.
    – wisbucky
    Apr 17, 2019 at 19:11
1

I worked around this problem using a shell script that auto-reloads less on exit:

while true; do less -K file.txt || exit; done

With this script, I can hit q to reload the file, and CTRL+C to exit back to the bash shell. The CTRL+C behavior is enabled via the -K option. Your last search term will be preserved.

This can be further refactored by using the colon (:) to create an empty expression, via do : ...

while less -K file.txt; do : ; done

Drawbacks

The current viewing position will always be rest to line 0.

Practical Example using mintty

In my windows (GitBash) environment I set up a script that opens a new terminal window (mintty) for less-viewing a file:

lesswin() { mintty bash -c "while less -K \"$@\"; do : ; done;" & }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.