If I want to find a file in a directory or somewhere under it, find is a very useful utility. Is there a similar utility that will find things in the current directory or above it?

For example, if my file system looks like this:

/proj/
   foo/
     pom.xml
     bar/
       pom.xml
       baz/
         pom.xml
   quz/
     pom.xml

then find /proj/foo/bar -name pom.xml will give me

/proj/foo/bar/pom.xml
/proj/foo/bar/baz/pom.xml

as it's output. I am looking for a command that would return

/proj/foo/bar/pom.xml
/proj/foo/pom.xml

(or the opposite order). What I currently tend to do is write a shell script that does something like

while [[ $dir != / ]]
do
  check stuff
  cd ..
done

Does something like this exist?

Ideally, I would like something that works on Linux, Mac and Cygwin in any shell, but something that works on a subset, or only in bash, is also useful.

  • Aaah...I misunderstood the request then. – EBGreen Jun 14 at 15:48
  • 1
    I think this is interesting and like the question.... Maybe this will help give you a starting point or you'll see a solution there that will suffice for your need: unix.stackexchange.com/questions/6463/… The accepted answer looks similar to your while loop example with some addition stuff. – Pimp Juice IT Jun 14 at 17:53

Not tested, but this should do it in bash (not sure about other shells):

#!/bin/bash
oldpwd=`pwd`
ret=1

while true; do
    find `pwd` -mindepth 1 -maxdepth 1 $@

    if [ $? -eq 0 ] ; then
        ret=0
    fi

    if [ `pwd` = '/' ] ; then
        exit $ret
    else
        cd ..
    fi
done

cd $oldpwd

As a script, it should accept regular find syntax for expressions. It saves off the current directory so it can jump back later, and then loops up the directory tree, searching only items at that level for the expression, up until it hits the root directory. This will print all matching items up the tree, you could easily add a check inside the loop to bail if find is successful if you just want the first matches.

It could probably be optimized a bit, but I went for quick and easy to understand over speed.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.