Become Root from Inside Vim – How to Use Sudo in Vim

rootsudovim

Sometimes I start editing configuration files in /etc using Vim, but forget to use sudo to start Vim. The inevitable result then is that after finishing my edits I encounter the dreaded notice that I don't have the permission to save the file.

Mostly the edits are small enough that I just exit Vim and do the whole thing again as root. I could of course save to a location I can write to and then copy as root, but that is also somewhat annoying.

But I'm sure there is an easier way to become root or use sudo from inside Vim, without having to discard the changes. If the method would not rely on sudo being set up for the user that would be even better.

Best Answer

sudo cannot change the effective user of an existing process, it always creates a new process that has the elevated privileges and the original shell is unaffected. This is a fundamental of UNIX design. I most often just save the file to /tmp as a workaround. If you really want to save it directly you might try using a feature of Vim where it can pipe a file to another process. Try saving with this command:

:w !sudo dd of=%

Tested and works. Vim will then ask you to reload the file, but it's unnecessary: you can just press o to avoid reloading and losing your undo history. You can even save this to a Vim command/function or even bind it to a key for easy access, but I'll leave that as an exercise to the reader.

Related Question