Navigating Maven projects on the command line

Or how to avoid..

~/dev/myproject/src/main/java/com/example/foo $ cd ..
~/dev/myproject/src/main/java/com/example $ cd ..
~/dev/myproject/src/main/java/com $ cd ..
~/dev/myproject/src/main/java $ cd ../../..
~/dev/myproject $

This following Bash shell function, which is called pom.. (yes with two dots in the name), will allow you to navigate up to the closest ancestor directory containing a pom.xml file (closest module) with one command. Put it in your ~/.bashrc:

function pom..() {
    local start_dir="$(pwd)" prev_dir= rel_dir="$1"
    while [ "$prev_dir" != "$(pwd)" ]; do
        cd ..
        if [ -f pom.xml ]; then
            if [ -d "$rel_dir" ]; then
                cd "$rel_dir"
            elif [ "$rel_dir" ]; then
                echo >&2 "Directory not found relative to pom.xml: $(pwd)/$rel_dir"
                cd "$start_dir"
                return 1
            pwd|sed "s#^$HOME#~#"
            return 0
    echo >&2 "No pom.xml found in ancestor directories."
    cd "$start_dir"
    return 1

So you don’t have to waste any more time typing “cd ..” multiple times when navigating upwards to a Maven module root on the command line. Just type pom.. once.

~/dev/myproject/src/main/java/com/example/foo $ pom..
~/dev/myproject $ 

It also accepts an optional argument, which is a desired directory relative to the nearest POM:

~/dev/myproject/src/main/java/com/example/foo $ pom.. target
~/dev/myproject/target $ pom.. src/test
~/dev/myproject/src/test $

The strategy will work for any style of hierarchically organized source code project where a typical marker file or directory exists at certain source code roots. Just be creative and modify the code.