A 'cd' Command for Git Projects

I often find myself in a project directory and one of two things usually happens. The first is that I would like to go directly to the top level directory of the project. The second is that I would like to go outside of the project directory and get back very quickly. Though not sophisticated, I came up with this simple shell script called cd-to-project-root.

#!/bin/sh

pushd . > /dev/null

until [ -d .git ] || [ `pwd` = '/' ]; do
    cd ..;
done

if [ `pwd` = '/' ]; then  # try to go to a project directory
    if [ -z $PREV_PROJECT_ROOT ]; then
        popd > /dev/null
        echo "Project directory not found.";
    else
        cd $PREV_PROJECT_ROOT
    fi
else  # at a project directory
    export PREV_PROJECT_ROOT=`pwd`
fi

I saved this in my “~/bin” directory and made an alias to it called cdp. It’s important to source the script, otherwise the shell variables will not retain their values when the script terminates.

alias cdp=". cd-to-project-root"

This allows me to type cdp to set the project directory, which is under git version control. Anytime I want to get back to the project directory, I type cdp.