Understanding the ‘-mindepth’ Option in Find Command

find

I am using the find command of bash, and I am trying to understand it since it is part of a code that I am using. In the code, the command in question is –

find -L $RAW_DIR -mindepth 2 -maxdepth 2 -name "*.bam" -o -name "*.sam" | wc -l

I have been trying to understand this command by searching its components. In esence, I thinking it is trying to find the number of files that end with .bam or .sam. I think -maxdepth 2 means to search for these files in this folder and its immediate subfolder.

What I do not understand is what mindepth -2 does in this case. I looked up mindepth, and the explanation given everywhere is –

"Do not apply any tests or actions at levels less than levels (a non-negative integer). '-mindepth 1' means process all files except the command line arguments."

To me this explanation is not very clear. Just like maxdepth -2means search for subfolders upto a depth of 2, what does mindepth -2 correspondingly mean, in simple language?

Also, if mindepth is just the opposite of maxdepth in terms of the direction (which would make intuitive sense), then how do I understand the fact that executing the command above on a folder that does have a .bam file leads to the output 0, whereas omitting the mindepth part of the command leads to the output 1 ?

Best Answer

Depth 0 is the command line arguments, 1 the files contained within them, 2 the files contained within depth 1, etc.

-mindepth N tells to process only files that are at depth >= N, similar to how -maxdepth M tells to process only files are at depth <= M. So if you want the files that are at depth 2, exactly, you need to use both.

Your command would match $RAW_DIR/foo/bam.bam, but not $RAW_DIR/bar.bam.

Try, e.g.

$ mkdir -p a/b/c/d
$ find ./a -maxdepth 2
./a
./a/b
./a/b/c
$ find ./a -mindepth 2
./a/b/c
./a/b/c/d
$ find ./a -maxdepth 2 -mindepth 2
./a/b/c

maxdepth with a negative argument doesn't mean anything:

$ find ./a -maxdepth -2
find: Expected a positive decimal integer argument to -maxdepth, but got ‘-2’
Related Question