1

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

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

  • Excellent! Thanks for that. Nice and clean. It's now an alias in ~/.bashrc: alias sudovimdiff='SUDO_EDITOR=vimdiff sudoedit'. – Sparhawk Feb 25 '15 at 1:14
1

Here is a fiddly solution. Please feel free to optimise it! Perhaps this might work in ~/vimrc?

Open both files with sudoedit

$ sudoedit file1 file2

Vertically split one buffer

:vsp | b2

In each window, run

:diffthis

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.