Bash find command not operating in depth-first-search

Viewed 127

So I read that the find command in Bash should operate with DFS, but I don't see it happening.

My path tree:

- tests_ex22 
     - first 
         - middle
              - story2.txt
         - story1.txt
     - last
        - story3.txt

I run the following command:

find $1 -name "*.$2" -exec grep -wi $3 {} \;

And to my surprise, elements in "middle" are printed before elements in "first".

When find arrives in a new directory, I want it to look in the current dir before moving to a new dir. But, I do want it to move in a DFS way.

Why is this happening? How can I solve it? (ofc, I don't have to use find).

2 Answers

middle is an element of first. It's not processing middle before elements in first; it's processing middle as part of the processing of first's elements.

It sounds like you want find to sort entries and process all non-directory entries before directory entries. There is no such mode, I'm afraid. In general find processes directory entries in the order it finds them, which is fairly arbitrary. If it were to process them in a particular order—say, alphabetical, or files before subdirectories—it would be required to sort entries. find avoids that overhead. It does not sort entries, not even as an option.

This is in contrast to ls, which does indeed sort its output. ls is designed to be more of a human-friendly display tool whereas find is for scripting.

Sort by depth

If you're mainly printing file names you could induce find to print each entry's depth along with its path and then manually sort by depth. Something like this:

find "$1" -name "*.$2" -printf '%d\t%p\n' | sort -V | cut -f 2-

You'll have to adapt this to your use case. It's tricky to fit the grep in here.

Manual loop

Or you could write a recursive search by hand. Here are some starting points:

Your example shows find operating in a depth first manner. If you want breadth first manner there's a tool that's compatible with find but breadth first that is called bfs.

https://github.com/tavianator/bfs

Related