I have a directory that have the r permission bit:

dr-------- 3 robert robert 4096 2017-12-17 03:47 dir

This directory have two files and one directory:

file 1.txt  file 2.txt  subdir

When I run the command ls dir (from the robert account), I get an error alongside the content of the directory:

ls: cannot access dir/file 1.txt: Permission denied
ls: cannot access dir/file 2.txt: Permission denied
ls: cannot access dir/subdir: Permission denied
file 1.txt  file 2.txt  subdir

Why ls displayed an error even though it also displayed the content of the directory without any problem?


ls calls readdir() (or getdents()) on the directory itself, which amounts to "reading" the directory. I think some Unixes implement this as actual calls to read(), as if the directory was a file. That works, since you have read permission to the directory, but it only gives the names of the files.

In addition to that, ls often wants to find the types of the files (to show different types with different colors, or to put the trailing slashes and asterisks etc. with ls -F). But finding the type generally requires calling stat() on the files themselves, and that requires access (+x) permission to the directory, in the same way actually opening the files would require. And you don't have that.

| improve this answer | |
  • For quite some time now the on-disk format of a directory isn't any simple list of names, and read(3) of directories is forbidden. – vonbrand Feb 3 at 12:43
  • @vonbrand, the kernel could still generate the results of the read() as a list of names. Perhaps only for backwards compatibility, but anyway. But I'm not sure, I seem to recall seeing that on some BSD, but I don't have any current ones to check on. – ilkkachu Feb 3 at 18:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.