Vimdiff – Is There a sudoedit Equivalent?

sudosudoeditvimvimdiffvimrc

I'm trying to get into the habit of editing root-owned files with sudoedit, instead of sudo vim. This has a few advantages, one of which is that it uses my user's ~/.vimrc.

Is there an equivalent, instead of using sudo vimdiff?

What I've tried

  • Instead of using vimdiff directly, one can open two files in vertical splits, then run :diffthis in both. However, if I open up one file with sudoedit, then I'd have to open the second file directly, instead of sudoedit automatically creating a copy of this file in /var/tmp.
  • One can also open files directly in splits using vim -O file1 file2. However, unsurprisingly, sudoedit -O fails.

Best Answer

To determine what editor to run, sudo checks three environment variables (in order): SUDO_EDITOR, VISUAL, and EDITOR, and uses the first editor it finds. (If it doesn't find one, it falls back to a default.)

So you can make it run vimdiff instead of vim as follows:

$ VISUAL=vimdiff sudoedit file1 file2

If your sudoers policy only lets you edit certain files, this might fail, in which case you can add a parameter:

$ VISUAL='vimdiff file1' sudoedit file2

In that case, I'm assuming you can read file1 as a normal user, but need root access to read file2.

(I'm using VISUAL because that's what I'm used to; feel free to use SUDO_EDITOR instead.)