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 to represent the name of the file.)

Then write the file using w! (The exclamation point is needed to make sure that the changes take place. Even though you changed permissions on the file, vi thinks the file is still read-only, because it was read-only when the file was originally opened.)

    :w!

Get WYNTK: UNIX System Admininistrator now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.