Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question

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.

share|improve this answer
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/*
share|improve this answer

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?

share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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