Read more

Vim: How to write a file you opened without sudo

Dominik Schöler
November 21, 2014Software engineer at makandra GmbH

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 %
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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!!
Posted by Dominik Schöler to makandra dev (2014-11-21 14:12)