Linux – Why is “rm -r” unable to delete this folder

linuxpermissionsrm

I have a folder with -wx permissions called folder1 and another folder inside it called folder2 with rwx permissions.

I tried to delete folder1 using this command:

rm -r folder1

But I got the following error:

rm: cannot remove 'folder1': Permission denied

The reason I think I got this error is because the rm program needs to first get the content of folder1 (get the names of the files and folders inside folder1 that is) in order to be able to delete that content (because you can't delete a file or folder without knowing its name I think), and then the rm program can delete folder1 itself.

But since folder1 doesn't have the read permission, then the rm program can't get its content, and hence it can't delete its content, and since it can't delete its content, then it can't delete it.

Am I correct?

Best Answer

I think your analysis is correct: you cannot delete the directory since its non-empty, and you cannot empty it since you cannot see its contents.

I just gave it a try:

$ mkdir -p folder1/folder2
$ chmod -r folder1
$ rm -rf folder1
rm: cannot remove 'folder1': Permission denied
$ rmdir folder1/folder2
$ rm -rf folder1
$ 

When I wrote “you”, I meant any program you may run. Your rm -r command first sees that folder1 is a directory, so it tries to discover its contents to empty it, but fails for missing read permission, then it tries to delete it but fails because it’s non-empty. The “Permission denied” is misleading; I think “Directory not empty” (like rmdir reports) would be more appropriate.)

Related Question