TIL: How to check and reset a directory tree of permissions with `chmod` and `namei`
I had an issue where a webserver wasn’t able to display a file due to file permissions. Once you’ve established that the file itself has correct permissions, you need to check every part of the parent path, in case there’s a directory that’s lost its read and/or execute permissions.
Until today, I’d never heard of the namei
command, which can do this for you in a single call.
If you’re on linux, you’ll should already have namei
installed (it’s in util-linux on Debian & Ubuntu), but on MacOS you’ll need to brew install util-linux
and because it installs keg-only, you’ll need to give it the full path $HOMEBREW_PREFIX/opt/util-linux/bin/namei
$ sudo -u nobody namei /path/to/problematic/file/that/wont/open.png
f: /path/to/problematic/file/that/wont/open.png
d /
d path
d to
d problematic
file - Permission denied
Here we’re calling namei
with the user the webserver runs as (nobody
) and checking it can read the full path to the file. If there’s an error it will show you which parts of the path have a problem.
In the example above, it’s the problematic
directory (directories are indicated with a d
, files with a f
) - there’s a permission denied error. In case later directories also have problems, I’m going to ensure all the correct permissions are present.
Again, until today, I had no idea that you could set the correct read and execute permissions; with files only having read (644
) and directories have read and execute (755
), using purely chmod
and not having to find -type d
to set the execute permissions.
Thanks to this Super User post on How to recursively chmod all directories except files? it’s a (complex) one liner:
chmod -R u-x,u+rwX,go+rX,go-w /path/to/problematic
All links, in order of mention:
- namei: https://linux.die.net/man/1/namei
- util-linux: https://github.com/util-linux/util-linux
- keg-only: https://docs.brew.sh/How-to-Build-Software-Outside-Homebrew-with-Homebrew-keg-only-Dependencies#what-does-keg-only-mean
- Super User: https://superuser.com
- How to recursively chmod all directories except files?: https://superuser.com/questions/91935/how-to-recursively-chmod-all-directories-except-files
Recent posts:
- Patch for aarch64 (aka arm64) openssl 1.0.2 'relocation R_AARCH64_PREL64 against symbol OPENSSL_armcap_P error'
- TIL: the `NO_COLOR` informal standard to suppress ANSI colour escape codes
- Copy the contents of a branch into an existing git branch without merging
- Adding search to a static Jekyll site using pagefind
- asdf, python and automatically enabling virtual envs