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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)