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 happens 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:


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 like, duh. At this point you either quit vim:


And open the file again with sudo:

$ sudo vim /etc/apache/httpd.conf

And make all the changes again. Or if you're a bit smarter, 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

Don't do that anymore! Use this command:

:w !sudo tee % >/dev/null

This command will save you hundreds of hours throughout your career. Here's how it works - 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 discards tee's stdout as you don't need to see it.

In fact, don't use this command as it's too too long and complicated to remember! Save another few hundred hours and create a vim alias for this command because you'll use it for the rest of your life. Put this in your ~/.vimrc:

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

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


See you!