Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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)

share|improve this question
    
related questions (not quite exact duplicates): superuser.com/questions/23428/vim-sudo-vim-bad-idea .. superuser.com/questions/106865/… .. and from SO, stackoverflow.com/questions/1005/… –  quack quixote May 26 '10 at 20:00
    
The SO is definitely a dupe, however the two SU questions address a separate problem solved with the sudoedit command. This question is more focused on forgetting to type it in the first place and elevating after starting the editor. –  heavyd May 26 '10 at 20:22

2 Answers 2

up vote 13 down vote accepted
: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

share|improve this answer
    
Thanks a lot, you made my life a lot better ! (Brian too) –  zimbatm Jun 8 '10 at 20:22
    
I've just added a second method. –  Marian Jun 8 '10 at 21:33
    
That's really neat! –  Anthony Giorgio Jan 11 '11 at 22:35

:w !sudo tee % >/dev/null

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.