Saving a read-only file edited with Vi/Vim
How to save a read-only file edited with Vi or Vim without losing your changes
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
Rather than being tempted to exit (ESC :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 %
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 ESC :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
That's it for this quite short first post. I hope this trick proves useful, as it saved my day earlier today :) Any comment is obviously more than welcome.