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?

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 what do you do?

Usually, you exit vim:

:q!

And open the file again with sudo:

$ sudo vim /etc/apache/httpd.conf

And make all the changes again.

So much time wasted!

If you're an intermediate vim user, then you 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.

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 anyone 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!