Linux – is there an ‘upwards’ find

findlinuxpathshell

I found I asked this question on the wrong stackexchange site.

To find files starting from a certain path, I can use find <path> .... If I want to find 'upwards', i.e. in the parent directory, and it's parent, and…, is there an equivalent tool?

The use case is knowing the right number of dots (../../x.txt or ../../../x.txt?) to use in e.g. a makefile including some common makefile functions somewhere upstream.

Intended usage for a folder structure like this:

/
/abc
/abc/dce/efg/ghi
/abc/dce/efg2


$ cd /abc/dce/efg/ghi
$ touch ../../x.txt
$ upfind . -name X*
../../x.txt
$ upfind . -name Y* || echo "not found"
not found
$ touch /abc/dce/efg2/x.txt
$ upfind . -name Y* || echo "not found"
not found
$ 

So in short:

  • it should search on this folder, it's parent, it's parent's parent…
  • but not in any of their siblings (like 'find' would)
  • it should report the found file(s) relative to the current path

Best Answer

You can use this simple script. It walks the directory tree upwards and seraches for the specified files.

#!/bin/bash
while [[ $PWD != / ]] ; do
    find "$PWD"/ -maxdepth 1 "$@"
    cd ..
done

Usage:

upfind -name 'x*'
Related Question