I was using Vim the other day as usual, when I noticed something strange. Here's what I did:
~$ touch testfile ~$ ls -l | grep testfile -rw-r--r-- 1 username groupname 0 Jul 23 10:00 testfile ~$ vim testfile
Then I made a change, and saved and quit with
:wq. Pretty normal. Then, however:
~$ sudo chown root:root testfile ~$ sudo chmod 644 testfile ~$ sudo -k ~$ ls -l | grep testfile -rw-r--r-- root root 0 Jul 23 10:02 testfile ~$ vim testfile
So root should have r/w access and everyone else should have only read. Edit the file, try to save - you can't. Awesome, working as intended. However, if you save with
:w!, vim somehow changes the file ownership back to username:usergroup and the file is saved. Even if you do this:
~$ sudo chmod 444 testfile ~$ sudo -k ~$ ls -l | grep testfile -r--r--r-- 1 root root 0 Jul 23 10:06 testfile ~$ vim testfile
You can still overwrite with
:w!! What is happening? How can vim break the laws of file ownership and permission like this? I looked at the help page in vim by saying
:help :w and found this:
:w[rite]! [++opt] Like ":write", but forcefully write when 'readonly' is set or there is another reason why writing was refused. Note: This may change the permission and ownership of the file and break (symbolic) links. Add the 'W' flage to 'cpoptions' to avoid this.
I've been unable to write to a file in vim previously when I shouldn't, so I guess the real heart of my question is, how can I make a file unedit-able by vim and why isn't it based on file system permissions, like I'd expect, and what mechanism is vim using to edit the file that other editors (gedit, nano) can't use?
EDIT: The computer I tried this on is using Linux kernel 3.15.5-2-ARCH. Vim's version number is 7.4.373-1, and it's the one installed by
pacman - I didn't compile it from scratch with any special options.