Vim: How to write a file you opened without sudo

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 Over 9 years ago