How to a user Edit a file even when Write bit is off on a file

filespermissionsvim

Here is the thing i just had a urge to play with umask on my training machine.

i created test user john and logged in using john. and set the umask to 0200 and created a testfile in vim and saved it. Now the permissions for this testfile are

-r--rw-rw-. 1 john john 26 Jun 28 12:25 testfile

Now i again tried to edit the file and entered some gibberish words.

Now when i try to save using ":wq" editor says file is readonly and can't be saved. But when i added exclamation mark at the end ":wq!" it saved the file.

What just happened ?? even when the write bit is off in testfile

Host OS = RedHat (rhel) 7.2

Best Answer

With "wq", "!" asks Vim to ignore the read-only attribute. From the documentation:

:wq [++opt] Write the current file and quit. Writing fails when the file is read-only or the buffer does not have a name. Quitting fails when the last file in the argument list has not been edited.

:wq! [++opt] Write the current file and quit. Writing fails when the current buffer does not have a name.

Note the difference: without "!", "fails when the file is read-only ..."; that no longer applies with "!".

As to why this happens technically, since you're the owner of the file, Vim can effectively ignore the permissions on it (at worst, it can change them and restore them). In practice Vim supports a couple of ways to write read-only files:

  • if the directory is writable, it will rename the existing file (adding ~ to its name), create a new file, write the new contents to that file, and restore the original file's permissions (this works even if the user running Vim isn't the owner of the file);
  • if the directory isn't writable, it will make a backup of the file to a writable directory (~/tmp typically), change the file's permissions to make it writable, write the new contents to the file, and restore its original permissions (the only works if the user running Vim is the owner of the file).
Related Question