Becoming root from inside Vim

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.


Saving the file as root:

:w !sudo tee %

Call sudoedit to edit files as root.

Think of the inconvenience when calling vim directly as a warning that you're being too casual in doing something potentially dangerous.

Tags:

Vim

Sudo

Root