The following find
command would find every leaf directory under the current directory, and execute a script within it:
find . -type d -links 2 -execdir /path/to/script.sh some arguments here \;
This would execute the command given to -execdir
in each leaf directory under the current directory.
The same, but using zsh
(does not consider hidden names):
for dirpath in ./**/*(/l2); do
( cd "$dirpath" && /path/to/script.sh some arguments here )
done
The pattern ./**/*(/l2)
would expand to the pathname of any leaf directories under the current directory. The **
matches recursively down into directory structures while *(/l2)
would match any name that is a directory with a link count of exactly 2 (i.e. it's a directory with no subdirectories, a fact also used by the find
command above).
Note that on some filesystems, like Apple's APFS, directories may have a link count greater than 2 even when they have no subdirectories. On BTRFS, the link count for directories is always 1. This solution would therefore not work on those filesystems.
Related:
()(($#)) $d/*(/DNY1) && continue
to avoid the temporarysub
variable. – Stéphane Chazelas Oct 04 '19 at 10:20