Bash · How To · Vim

Saving read only files in Vim

Ever had a situation where you opened a file for editing, made some changes, and discovered that you don’t have the rights to write the file? This happens to me.

It usually goes like this.


I open a file without using sudo:

$ vim /etc/apache/httpd.conf

I make many changes and then type:


And I get an error:

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

And then I go like, huh. At this point I either used to quit vim:


And open the file again with sudo:

$ sudo vim /etc/apache/httpd.conf

And make all the changes again. Or sometimes save the file to /tmp directory:

:w /tmp/foo

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

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

I don’t need to that anymore! Now I use this command:

:w !sudo tee % >/dev/null

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.

Did you find this command too long and complicated to remember! Create an vim alias then :


Put this in your ~/.vimrc:

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

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



Leave a Reply

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

You are commenting using your 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