Reverse Find

I recently had need to do a reverse find, and couldn’t discover any programs that offer this functionality. I decided to work around the issue using a bash function, loops, and find.

This function can be stuffed into your ~/.bash_profile, and referenced wherever you need it.

rfind()
{
    rfind_path="${PWD}"
    while [[ "${rfind_path}" != "/" ]]; do
        rfind_search_paths="${rfind_search_paths} ${rfind_path}"
        rfind_path=$(dirname "${rfind_path}")
    done
    
    find ${rfind_search_paths} / -maxdepth 1 $@ -print -quit
}

As an example, let’s say I’m in /home/user/docs, and I execute rfind somefile.txt. rfind will actually build a command and execute the following:

find /home/user/docs /home/user /home / -maxdepth 1 somefile.txt -print -quit

This will find the nearest parent directory containing a file called somefile.txt, and quit after printing the first (nearest) match.

Edit: Updated rfind to use a much simpler dirname method.