How to overwrite read-only files with vim

We can file this post into the category of “stuff I’ve known how to do for a long time, but I was shocked I hadn’t put out a post discussing it before”.

If you use Vim or Neovim as much as I do, you end up touching a lot of files in a lot of different places. If you’re editing certain system files, they may be flagged as read-only, and if so, Vim makes you take an extra step to be able to save the file.

First and foremost, if you’re editing a file that you don’t own or have rights to edit, you’ll need to make sure to elevate your privileges with su or sudo. Once you’ve done that, go ahead and edit your file as you normally would.

When you go to save the file with :w or :wq, you should be greeted with a lovely error:

E45: 'readonly' option is set (add ! to override)
Zsh

Funny story, the first time I ran into this, back in the 1990s, my first inclination was to try to save the file with :!w, which ends up dumping out some information about the process and user and other system stuff. Oh how far I’ve come.

All right, back from my trip down memory lane, all you need to do is exactly what the message said, which is ADD the band at the end:

:w!
Zsh

Assuming you have the right permissions, you’ll be able to save the file. If you don’t have the right permissions, you’ll be given an error about that.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.