Saving a read-only file edited with Vi/Vim




It may sometimes happen that you open a system file for edition, forgetting (or not seeing the warning) that the file is actually read-only. Then you make a couple of changes, then try to write the file.
A nice message then pops up: Can't open file for writing

Error message when opening protected file

Rather than being tempted to exit (q!), lose your changes, reopen the file with sudo (sudo vim /path/to/my/system/file) and editing it again, you can use the following interactive command right in Vi/Vim to write your changes:

ESC :w !sudo tee %

Interactive save

This command will ask for your password, then you will be able to acknowledge the buffer changes or reload the file to its initial state.

At this stage, you will be presented with the content of the file and a prompt to press ENTER or type another command.
Then type the letter O to simply save the file and move on.
Note that pressing L seems to do pretty much the same thing. The file will be saved but remains opened in Vi/Vim for more editing or reading. We can now exit normally by typing :q! since the file is still opened as read-only.

For reference, below is what those commands actually mean and do:

  • :w : Write
  • !sudo : Invoke a shell with the sudo command
  • tee : the output of the write command above
  • % : the current file path