Should Sudo Less Change Ownership of ~/.lesshst? – Explained

lesssudo

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.

Best Answer

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).