How can I write a bash-function that finds a specific parent directory. Here's my setup:


The app-server used for devs is located at:


I'd like to have a bash function that goes up recursively to the branch's root to quickly copy compiled modules to the appserver, run/stop the appserver, call specific maven goals etc.

Any ideas? Each branch has a maven pom.xml which contains exact information about the version


How about:

find_branch_root () {
    while [ ! -e "$cwd/pom.xml" ] && [ "x$cwd" != x/ ]; do
         cwd=`dirname "$cwd"`
    echo "$cwd"

Peals off directories from the path until either root (/) is reached or "pom.xml" is found.

  • You can save a process by replacing dirname "$cwd" with cwd=${cwd%/*}; cwd=${cwd:-/}.
    – jw013
    Jan 13 '12 at 15:09

Make a exported env var with a name like PRJDIR which has a value like /home/user/dev/project1. This env var can easily referenced by further scripts kike this:

cp ${PRJDIR}/modules/* modules/*

Maybe a while loop that does cd .. unless/until it finds an appropriate file or directory, then does cd down into the new directory structure putting you in the correct place? Would that not work?

  • A function is asked for; doing a cd in a function changes the current directory in the calling shell as well, which is likely not what is wanted.
    – Arcege
    Jan 13 '12 at 14:41
  • @Arcege The function could save and restore the cwd, and even $OLDPWD to be extra thorough.
    – jw013
    Jan 13 '12 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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