Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Possible Duplicate:
Becoming root from inside Vim

It could happen to anyone. The admin types:

vi /etc/resolv.conf

as a regulare user. He edits the /etc/resolv.conf file, but when he wants to hit :x he suddenly notices that he was editing the file in read-only mode because he opened it with a normal user, not root.

Are there any vi commands to get root priviledges, so that the admin wont have to hit :q! and sudo su - and vi /etc/resolv.conf and edit it again?

share|improve this question

marked as duplicate by Michael Mrozek Jan 4 '12 at 22:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

OT, but sudo vi /etc/resolve.conf should be sufficient, no need to start a root login shell. – Mat Jan 4 '12 at 8:17
I'd probably just write the buffer to a temporary file, then quit and sudo vi .... It doesn't quite do what you asked, but it avoid having to re-enter the changes you've made. – Keith Thompson Jan 4 '12 at 9:09
I asked the same question about Vim a while ago:… – Mad Scientist Jan 4 '12 at 15:07
"sudo su -"? Read "man sudo", please. – Jürgen A. Erhard Apr 14 '12 at 17:47

1 Answer 1

up vote 43 down vote accepted

In the page Top Ten One-Liners from CommandLineFu Explained is suggested this trick (the #3):

:w !sudo tee %

this write the current buffer to the stdin of the command after the !. The % symbol is substituted with the current filename.

share|improve this answer
Oooh, nice. Will have to remember that. – Shadur Jan 4 '12 at 8:48
A discussion about this very trick:… – Nathan Long Jan 4 '12 at 15:33
What will happen if sudo asks you to enter your password? Will this be managed by vi / vim? – Giorgio Jan 4 '12 at 15:55
you simply write your password then, and it goes on – LanceBaynes Jan 4 '12 at 17:13
As retrieved from @Fabian's question, the more correct way to do this is :w !sudo dd of=% because the way above is an exploit of tee, but in practice either works fine. – user606723 Jan 4 '12 at 17:53

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