3

Mission: List all direct decendants of a directory that are a directory itself.

On BSD (Mac OS), find . -type d -depth 1 works.

This is the output of Ubuntu 12.04 (GNU findutils 4.4.2):

$ find . -type d -depth 1
find: warning: you have specified the -depth option after a non-option argument -type,
but options are not positional (-depth affects tests specified before it as well as 
those specified after it).  Please specify options before other arguments.

find: paths must precede expression: 1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Ok, next try:

$ find . -depth 1 -type d
find: paths must precede expression: 1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Hrm, well, maybe it wants...

$ find -depth 1 . -type d
find: paths must precede expression: 1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Apparently not, wtf, should it need...

$ find . -depth=1 -type d
find: unknown predicate `-depth=1'

Nah, this was obvious. So lets try as last resort...

$ find . -mindepth 1 -maxdepth 1 -type d
<my directories>

Yay, success! But, erm, why...?

And, as a bonus question, why is -mindepth 1 -maxdepth 1 so much faster than -depth 1 on BSD / OSX?

Thomas Keller
  • 5,933
  • 6
  • 48
  • 80

2 Answers2

4

Different versions of find use the -depth primary to mean completely different things:

  • -depth means perform a depth-first search (i.e. visit the contents before the directory itself). This is different from most primaries, as it doesn't control which files are matches, but how the search is performed. As far as I know, all versions of find support this.

  • -depth n means match only items at a depth of n (i.e. what you want). This is a completely different meaning from -depth when it isn't followed by a number, which can be very confusing. Also, not all versions of find support this (OS X's does, GNU findutils' apparently doesn't).

The -find n primary is useful, but unfortunately not portable. If you need portability, I think you're stuck with -mindepth n -maxdepth n.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
2

The -depth option does not take an argument:

-depth Process each directory's contents before the directory itself.

Options like -name, -type expect to be followed by something, this does not apply to -depth. It is more of a boolean option.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • 1
    Hrm, I should have RTFM then, thanks for the pointer. The BSD man page tells me `-depth n: True if the depth of the file relative to the starting point of the traversal is n.`. Apparently I misused this option for years, damn... – Thomas Keller Feb 26 '14 at 16:07