Vim: How to write a file you opened without sudo

Updated . Posted . Visible to the public.

Have you ever opened a file with vim, edited it and when you wanted to save your changes it told you "Can't open file for writing", because you opened it without sudo? There's an easy hack to let you write it anyway:

:w !sudo tee %

The linked SO post explains in detail what will happen.

Create a shortcut

If you're already used to the "exit vim, run vim with sudo again (sudo !!) and save" workflow but can't remember the above command, you may create an easy-to-remember shortcut. Add this snippet to your .vimrc:

" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %

... then write a file with sudo using

:w!!
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2014-11-21 13:12)