3

I want to execute a find search with multiple maxdepths, depending on the directory.

Is this possible? It seems that -maxdepth is "global", but I was curious if there is some workaround.

(I'm aware it's possible to execute two separate commands, but using one would be faster, and it would keep the calling code simpler)

  • Why not use two find commands? – pfnuesel Sep 10 '17 at 15:41
  • I've considered that, but before that, I wanted to try a single run, for both performance and sorting reasons. – Marcus Sep 10 '17 at 15:42
  • 3
    It would not keep the code simpler. – Kusalananda Sep 10 '17 at 15:48
  • FreeBSD find supports syntax like find dir1 dir2 \( -path 'dir1/*' -depth 1 -prune \) -o \( -path 'dir2/*' -depth 2 -prune \) -o -print – Tavian Barnes Sep 12 '17 at 20:38
  • @TavianBarnes this is in fact the answer given below :-) – Marcus Sep 13 '17 at 21:19
7

You can sort of emulate it using -prune on different matching pathnames. For example, to match /etc to depth 1, and /lib to depth 2:

find /etc /lib/ \
    \( -regex '/etc/[^/]*/.*'       -prune \) \
 -o \( -regex '/lib/[^/]*/[^/]*/.*' -prune \) \
 -o -print

You need to be careful to add the last line to print or otherwise operate on the remaining files and directories.

5

No, you can’t apply different -maxdepth options to different parts of a series of find tests. Since it’s a global option, as you point out, it applies to all the tests. If you specify multiple -maxdepth options, the last one is taken into account and applied to the whole command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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