Recursing through directories from the bottom up with find

Only very recently did I learn to use find, and only today did I come to appreciate it.

I had this directory that originally came from a fat32-formatted disk – as a result, all file permissions were wrong. It’s a bit silly to have all kinds of documents marked executable and not made readable to other users. So I thought I could get somewhere using

chmod -R a+rX .

which would recurse down and make all files world-readable and only directories executable (that is, accessible). Well, not quite: the a+X also makes any file that was already executable for some user now executable for anyone (see chmod man page). So… what you’d really want to do first now is

chmod -R a-x .

…and there’s the problem: take away the x bit on the top-level directory, and you can no longer recurse. What you really want is to recurse through subdirectories first and then change the permissions on the directories themselves. Now, find lets you do exactly that, with the -depth switch. Here’s what I ended up doing:

chmod -R a+rx .

find -depth -exec chmod a-x {} \;

chmod -R a+X .

This makes everything accessible/executable first so that we can access everything when running the next line, which then removes that permission starting from the deepest part of the directory tree. The last line can now finally do what I meant to do all this while…


%d bloggers like this: