Save a file (that requires root permissions) from within vim editor
Himanshuz.chd 270004408M Comments (2) Visits (28926)
Have you ever got stuck in a situation where-in you opened and edited a file in vim editor but when you tried to save the changes then the following error was thrown by vim :
E45: 'readonly' option is set (add ! to override)
Well, I encountered this error quite frequently as I usually forget to do a 'sudo' while opening files that require root permissions for editing. Those who have experienced this issue might know how annoying it may get. I have recently found the solution to it so I thought to share it here.
Consider the file 'root_file' :
$ ls -lart root_file -rw-r--r-- 1 root root 43 Nov 6 07:14 root_file
So we see that this file requires root privileges to get edited. Now suppose this file is being edited in vim editor without any root permissions. As the user tries to save the file in vim editor (through :w ), here is the error that comes up :
So we see that the error (in RED) appears at the bottom of the vim editor window.
The solutionHere is the way through which root privileges can be acquired and the file can be saved from within the vim editor window.
Instead of saving the file through :w use :w ! sudo tee %
Now, when enter is pressed, a prompt appears asking for root password.
At this point, press any key.
Now press 'O' and you will see that the updated file appears in the vim editor window.