Write vim file as super-user

vim

This is a usability problem that happens often to me:

I open a read-only system file with vim, even editing it, because I'm not attentive enough, or because the vim on the system is badly configured. Once my changes are done, I'm stuck having to write them in a temporary file or losing them, because :w! won't work.

Is there a vim command (:W!!!) that allows you to write the current buffer as a super-user? (Vim would ask for your sudo or su password naturally)

Best Answer

:w !sudo tee % >/dev/null`

Explanation: With !, you can execute programs. By prefixing it with :w, the file's content (the stuff you have in vim, not the original file, more precisly: the buffer) will be given to the command on standard input. % is replaced by the file name, and the >/dev/null avoids that the content is again printed to the screen (which is the usual behavior of tee).

I've found an even shorter way. dd does not print to stdout so you can save the null thing.

:w !sudo dd of=%

​‍

Same is for :r, which inserts the output of the given command, so you can for example insert the current date into your file by using :r !date

Related Question