Quick Tip #5: Navigating in Source Trees

I often move around in checked out Subversion or Git source trees on a Bash command line. Directory structures tend to get quite deep (especially in Java projects), so one problem keeps coming up frequently: Changing back to the base directory of the source tree. Typing "cd .." ten times is tedious. Some people use their "..", or "...", or even "...." aliases for that, but there’s a more elegant way.

Add the following function to your ~/.bashrc file:

cdb() {
  pushd . > /dev/null

  while [ ! \( "$PWD" = / -o -d .svn -o -d .hg -o -d .git \) ]; do
    cd ..
  done

  if [ "$PWD" = / ]; then
    popd > /dev/null
  else
    popd -n > /dev/null
  fi
}

The function saves the current working directory on the directory stack and then changes to the parent directory until it finds a .svn (Subversion), .hg (Mercurial), or .git (Git) directory, which indicates that we’ve reached the top directory of the source tree.

The loop also stops at the root directory in case you execute it from somewhere that is not a revision-controlled source tree. In this case, we change back to where we started using popd, so executing the function is a no-op. If things worked out fine we throw away the cached directory on the stack and we’re done.

Note that this algorithm doesn’t work for Subversion 1.6 or older since these versions have a .svn directory on each level.

Advertisements
This entry was posted in shell and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s