4

I've been given a script to run, but it produces an error when calling find . -depth 1 -type d. It produces the following error,

find: paths must precede expression: `1'

This is the line in which it fails,

for dir in `find . -depth 1 -type d`
do
    ....

I have tried quite a few things without success. And I don't really see why it gives the error since it seems to me at least, that the paths does indeed precede the "1".

1

2 Answers 2

9

The -depth switch does not take an argument, but -maxdepth does, so:

for dir in `find . -depth -maxdepth 1 -type d`
do
    ....

should work.

The -depth argument as per the man page means process directory contents first.

1
  • If all they want to do is find directories in the current directory, they could do that with for dir in */; do ...; done with the dotglob and nullglob shell options set. Don't loop over output of find.
    – Kusalananda
    Commented Sep 26, 2022 at 20:35
3

That command is written for the FreeBSD version of find (or similar), and you're running it with another find that doesn't support -depth n. Probably the GNU one, based on the error message. The FreeBSD version has two -depth options (man page):

-depth
Always true; same as the non-portable -d option. Cause find to perform a depth-first traversal, i.e., directories are visited in post-order and all entries in a directory will be acted on before the directory itself. By default, find visits directories in pre-order, i.e., before their contents. Note, the default is not a breadth-first traversal.

-depth n
True if the depth of the file relative to the starting point of the traversal is n.

That first one is standard(*), the second isn't. Since the standard one doesn't take an argument, and lone arguments (paths) can't be given within or after the find expression (as you saw), the FreeBSD version can somewhat get away with overriding the name. (It might still be error-prone in that forgetting the argument to -depth would change the meaning.)

GNU and Busybox have the equally non-standard -mindepth n and -maxdepth n which when together can be used to require a particular depth:

find . -mindepth 1 -maxdepth 1 -type d

Note that you probably shouldn't use for f in $(find ...), as you'll face issues if any filenames contain whitespace.

See:

(* Like the text implies, the name -depth is inaccurate for a pre-/post-order switch.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .