0

I just set a read only permission to a file using chmod 400 filename.txt after that I open the file via vi editor and edit and try to save using :w then is says E45: 'readonly' option is set (add ! to override) so I use :w!. Then it save the edited file with read only permission? How can it be possible?

Are there any differences between Ubuntu and Fedora that affect access permissions?

1
  • Does :w! not successfully save readonly files in Fedora's vi? Aug 28, 2014 at 3:46

2 Answers 2

5

I ran vim using strace. I created a file in /tmp named "abc" with content "foo", set it read-only (chmod 400 abc), opened it in vim (strace -o vim.log vim abc) and saved it using ":wq!".

Here is the strace log:

...
getcwd("/tmp", 4096)                    = 5
write(1, "\33[?25l\"abc\"", 11)         = 11
stat("abc", {st_mode=S_IFREG|0400, st_size=4, ...}) = 0
getxattr("abc", "system.posix_acl_access", 0x7fff5725fd60, 132) = -1 ENODATA (No data available)
stat("abc", {st_mode=S_IFREG|0400, st_size=4, ...}) = 0
getuid()                                = 1000
chmod("abc", 0100600)                   = 0
open("abc", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 9
write(9, "foo\n", 4)                    = 4
fsync(9)                                = 0
close(9)                                = 0
chmod("abc", 0100400)                   = 0
setxattr("abc", "system.posix_acl_access", "\x02\x00\x00\x00\x01\x00\x04\x00\xff\xff\xff\xff\x04\x00\x00\x00\xff\xff\xff\xff \x00\x00\x00\xff\xff\xff\xff", 28, 0) = 0
...

We can see that vim calls stat to get the current permission, then the equivalent of chmod(u+w), then the write, then it restores the original permissions (in this case, chmod(400)).

1

If the file belongs to you, you can always change permissions on the file by calling chmod. I guess editor just alters permissions implicit, saves and reverts permissions. To really forbid writing, you should change file owner too.

1
  • 1
    On a related note, if you don't have write permissions on a file but you have write permissions on the directory the file is in, then you can still delete the file then recreate it (or create a new file and then rename it so it overwrites the old file). A lot of utilities do this in the normal course of editing any file, for example rsync does this when writing to a file - and therefore is unaffected by not having write access to a file. Therefore giving only read permission on a file to somebody, when you still give them write permission to the directory, is pretty ineffective. Aug 28, 2014 at 3:51

Not the answer you're looking for? Browse other questions tagged .