POSIX Find – Limit Search to Specific Depth

findposix

I noticed recently that POSIX specifications for find do not include the -maxdepth primary.

For those unfamiliar with it, the purpose of the -maxdepth primary is to restrict how many levels deep find will descend. -maxdepth 0 results in only command line arguments being processed; -maxdepth 1 would only handle results directly within the command line arguments, etc.

How can I get the equivalent behavior to the non-POSIX -maxdepth primary using only POSIX-specified options and tools?

(Note: Of course I can get the equivalent of -maxdepth 0 by just using -prune as the first operand, but that doesn't extend to other depths.)

Best Answer

You can use -path to match a given depth and prune there. Eg

find . -path '*/*/*' -prune -o -type d -print

would be maxdepth 1, as * matches the ., */* matches ./dir1, and */*/* matches ./dir1/dir2 which is pruned. If you use an absolute starting directory you need to add a leading / to the -path too.