10

Having performed a

sudo less ...

... in order to view a restricted log-file and doing some searches with it, I found the ownership and group of my ~/.lesshst file changed to root:root (where ~ refers to the home-directory of the user invoking the sudo command, not the home of root, obviously).

This is happening on a fresh Ubuntu 18.04 install with less --version:

less 487 (GNU regular expressions)
Copyright (C) 1984-2016  Mark Nudelman

I could find (google) no references of anyone observing, let alone explaining this behaviour anywhere; so I'm looking for either a rationale for it here or confirmation that it is simply sign of a bug.

16

This is normal.

sudo less ...

runs less as root, but without changing the home directory. Running searches causes the search history to be updated in ~/.lesshst, which changes the ownership of the file to the current user, root (to ensure the update can be done safely, less writes the history to a new temporary file, then renames it; this causes the original file’s ownership to be lost).

If you want to avoid this, you can tell less to use root’s history, by telling sudo to set the HOME variable to point to root’s home directory:

sudo -H less ...

Another option is to temporarily disable the search history:

sudo LESSHISTFILE=- less ...

This does however mean that you won’t be able to use the stored search history (/ followed by , or even n without specifying a search string).

  • 3
    Having now learned about the underlying mechanics, I suppose yet another way to solve this issue for more $HOME-dwelling utilities than just less, is to visudo a Defaults always_set_home line into etc/sudoers as learned from this and these answers – cueedee Oct 31 '19 at 10:51
  • 5
    Yes, that would work too, at the cost of some other surprises until you get used to it — other tools will also stop reading their settings from your home directory when used with sudo. – Stephen Kitt Oct 31 '19 at 11:03
  • 8
    This is also one place where the "useless use of cat" may be useful. I.e sudo cat ... | less runs less as current user, keeping any history in the user's .lesshst file, and not breaking its permissions. – pizzapants184 Oct 31 '19 at 23:04
  • 3
    @pizzapants184, that wouldn't be easily made to work when less gets invoked indirectly, like from a sudo git log for instance... but directly, yes certainly! – cueedee Oct 31 '19 at 23:53

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.