If you have already made edits when you learn the file is read-only, you can still save your changes.
Sometimes you don’t find out that you lack the permission to change a file until you’ve already made changes in the editor. When you open a read-only file for editing, you usually see some indication that the file is read-only. For example, in vi, you’ll see this message at the bottom of the screen:
"who.out" [Read only] 57 lines, 2742 characters
But you might not always notice the messages before you start making changes. The first time you find out that the file isn’t writable is when you try to save changes:
"who.out" File is read only
And when you try to quit, you’ll find out that your changes haven’t been saved:
No write since last change (:quit! overrides)
It looks as if your changes are lost. But they don’t have to be.
One thing you can do is save your changes under a different filename. For example:
:w ~/tmp
Then quit out of vi and have the permissions on the file changed. Once the permissions are fixed, you can copy the tmp file back over the original, and your changes have been saved.
If you own the file, you can save the changes without exiting the editor. First run a subshell to use chmod to change permissions:
:!chmod u+w %
(In vi, % can be used ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access