How come I can append to files to a directory without write permissions

directorypermissions

I understand this first example:

> mkdir foo
> chmod u-w foo
> touch foo/test
touch: cannot touch `foo/test': Permission denied
> echo "BAD" >> foo/test
bash: foo/test: Permission denied

This makes sense: I don't have write permission on the directory so I shouldn't be able to write any changes. I can not touch nor create a file that can be appended to. Why does this work however?

> mkdir bar
> touch bar/test
> chmod u-w bar
> echo "BAD" >> bar/test 
> cat bar/test 
BAD

Best Answer

You have no write permission on the directory. That means you cannot modify the directory. Creating or removing a file in the directory (which includes creating or deleting a file, as well as moving the file in or out of the directory) modifies the directory. If you modify a file inside the directory (by appending or overwriting it), that doesn't modify the directory itself.

You can also modify the file's metadata (dates, permissions, etc.) as long as you own the file, regardless of the permissions on the directory and on the file. You can even indirectly modify a file's access time by reading it, even if reading is the only permission you have on the file. Access to file metadata isn't controlled by permissions.

The only permission on the directory that's relevant to modifying files inside it is the execute permission. It controls whether you can access the file at all. (The read permission on the directory controls whether you can list the directory's files; with read but not execute, you can see the file names but not access the files; with execute but not read, you can access files in the directory, but only if you know their name.) As long as you can access the file, the directory's permissions don't matter further.

If you want to make a whole directory tree read-only, you can't do it by changing the permissions on the directory alone, you have to change the permission of every file. Alternatively, create a read-only view.

Related Question