Why can I remove a file as user which is owned by root?

As the title says: Why can I remove a file as user wich is owned by root?

Here is an example:

% sudo touch ~/test

% ls -la ~/test    
-rw-r--r-- 1 root root 0 Jun 18 20:31 /home/aboettger/test

% rm ~/test
rm: remove write-protected regular empty file ‘/home/aboettger/test’? Y

% ls -la ~/test
ls: cannot access /home/aboettger/test: No such file or directory

Because unlinking a file needs write access on the containing directory. One can indeed get this indirectly by dint of owning the directory, since if one is the owner one can always grant onesself write access. But in this case you'll find that your home directory is, already, writable by you. Ownership of the directory is not the necessity. Write access is. That includes write access via "other", via group membership, or via an ACL entry, where they apply.


If you have sufficient permission (rwx) in the directory, you can remove any file inside that directory.

Basically the directory entry contains a table having the file names it has and their inodes. So when a rm command is given the file entry is simply removed from that directory table, it does not depend on the owner of the files themselves. Just sufficient permission on the parent directory is enough.

Although the file remains valid in the filesystem until all the processes using the file completes.

The associated system call is unlinkat(). For example while removing the file.txt:

unlinkat(AT_FDCWD, "file.txt", 0)       = 0