Is there a way to find a file in an inverse recursive search?

#!/bin/bash

function upsearch () {
    test / == "$PWD" && return || test -e "$1" && echo "found: " "$PWD" && return || cd .. && upsearch "$1"
}

This function will walk up from the current dir. Note, that it is a function, and will change the directory, while traversing. It will stop in the directory, where it finds the file, and will walk up to the root / if not.

You might want to change it to a script instead of a function, and maybe jump back, if the file isn't found in the root directory.

If you never want to cd to the dir:

upsearch () {
  slashes=${PWD//[^\/]/}
  directory="$PWD"
  for (( n=${#slashes}; n>0; --n ))
  do
    test -e "$directory/$1" && echo "$directory/$1" && return 
    directory="$directory/.."
  done
}

This will lead to results like /home/cory/a/b/c/../../../happy if the file is in /home/cory/. If you need a cleaned path, you could do some

cd "$directory"
echo "$PWD"
cd - 

on success.

To restrict the search to regular files and excludes directories, symbolic links and the like, you can change the tests to -f instead of -e.

Tags:

Bash

Find