Vim: writing to read-only protected file

More than once I’ve opened file for edition, made my changes and tried saving to learn that it’s

A) read-only (Vim actually let’s you know as soon as you open it)
B) privileged, and my user without elevation didn’t have the rights

A is easy, :w!, there, done. So, often I don[t pay heed to Vim’s warning here.

B however bites you right then and there. You hit save and learn Vim can’t open the file for writing. Even with forced save (:w!). At first I copied the changes, reopened file again and applied them. But, for quite some time I’ve been using this little gem and since even during Anonymous Admin meetup it was met with loud ovation, I’m publishing it, for apparently it’s not so known:
:w !sudo tee %

Which roughly translates to:

write result of the command with current buffer as parameter.

Command is elevated tee. Running man tee we get:

tee - read from standard input and write to standard output and files

Standard input is % which in Vim-parlance means “current buffer”. AKA, what you would copy and paste.

So, again:
:w !sudo tee %

Writes result of command after !, which here is: elevated tee (stdin -> stdout and files) on current buffer (%).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s