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

/home/user/dev/project1/branch1/deeply/nested/module/structure

The app-server used for devs is located at:

/home/user/dev/project1/branch1/apps/someappserver

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 () {
    cwd=$PWD
    while [ ! -e "$cwd/pom.xml" ] && [ "x$cwd" != x/ ]; do
         cwd=`dirname "$cwd"`
    done
    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:

stop-app
cp ${PRJDIR}/modules/* modules/*
start-app

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 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.