Saving Files as root From Inside VIM

Oftentimes I will be editing a Linux configuration file using vim only to discover that I cannot save it because the file requires root permission to write to it. This ends up looking something like this:

[sourcecode lang="bash"]
vi /path/to/some/file.conf
[make some edits]
:w
VIM Message: E45: 'readonly' option is set (add ! to override)
:q!
$ sudo vi /path/to/some/file.conf
[make all my edits AGAIN]
:w
[/sourcecode]

I have gone through this process so many times that I knew there must be an easy fix for it. (I know about sudo !! for running the previous command, but I only recently started developing the habit of using it.) After forgetting to use sudo while editing a configuration file yet again this morning, I finally decided to search Google and find a solution. Here it is:

[sourcecode lang="bash"]
vi /path/to/some/file.conf
[make some edits]
:w
VIM Message: E45: 'readonly' option is set (add ! to override)
:w !sudo tee %
[/sourcecode]

The :w !sudo tee % command tells VIM to write the file (w) but run the sudo command first (!sudo) and read the writing of the file from standard input to standard output (tee) using the same filename as the one we're editing (%).

After saving the file as root, you'll get this message: "W12: Warning: File "/private/etc/smb.conf" has changed and the buffer was changed in Vim as well". You'll be given the option to reload it, but since you were already looking at the new version it doesn't much matter which option you choose (OK or Reload).

And last but not least, if you don't want to remember the syntax for this command, you can map the command in your ~/.vimrc file:

[sourcecode lang="bash"]
cmap w!! w !sudo tee % >/dev/null
[/sourcecode]

Now, if you forget to edit a file with sudo, you can simply type :w!! to fix the problem!