How many times have you had a situation when you open a file for editing, make a bunch of changes, and discover that you don't have the rights to write the file? This has happened to me a lot.

It usually goes like this.

You open a file and you forget to use sudo:

$ vim /etc/apache/httpd.conf

You make many changes and then you type:

:wq!

And you get an error:

"/etc/apache/httpd.conf" E212: Can't open file for writing
Press ENTER or type command to continue

And then you go FFFFFFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUCCCCCCCCCCCCCCCCKKKKKKKKKKKKKKKKKKK!!!!!!!!!

At this point you usually smash your computer with a hammer and quit your job.

But, if your nerves are calm, you exit vim:

:q!

And open the file again with sudo:

$ sudo vim /etc/apache/httpd.conf

And make all the changes again.

Or, another approach you take is save the file to /tmp directory:

:w /tmp/foo

And then you sudo move the /tmp/foo to the right location:

$ sudo mv /tmp/foo /etc/apache/httpd.conf

That works but here's another method that you can use without quitting vim:

:w !sudo tee % >/dev/null

Here's how it works. The first part:

:w !...

Means – write currently open file to stdin of command ....

In this case the command is sudo tee % >/dev/null. The special symbol % means the filename of currently open file.

So what happens here is vim spawns sudo tee FILENAME and pipes the contents of the file to its stdin. The tee command now runs in a privileged environment and redirects its stdin to FILENAME. The >/dev/null part discards tee's stdout as you don't need to see it in vim.

If someone asked me to write this command, I wouldn't be able to. It's too long and complicated to remember. Instead, create a vim alias for this command. Put this in your ~/.vimrc:

cnoremap sudow w !sudo tee % >/dev/null

Now the next time you're in this situation, just type:

:sudow

See you next time!