vim: Can’t open file for writing?!

You forgot to sudo vi and tried to write a file, and you got the above message. Oh no! How are you going to save that file now?

Well, you could write the file to your home directory and then sudo cp it into place. Or you could throw away your edits, quit, sudo vi, and then re-edit and save.

But here’s something even better:

Normal Mode:

:w !sudo tee %

This pipes the contents of the current file to the command tee running as root. % is a placeholder for “the name of the current file.” If you haven’t sudo’d recently you’ll be prompted for your password.

Your file has now been written, carry on!

Tagged as: vim vi cli intermediate

Hey — thanks for reading!

My name is Fred, and I'm a web developer by trade, Linux sysadmin by necessity. I want you to win at hosting your own web applications.

Server administration doesn't have to come with a side of stomach ulcer.

As a developer you've got most of the skills you need, all you need are some practical ways to up your server game.

Questions? Email me.