Incite Code

Blog of a Rails Developer

Git Branch Shown in Command Prompt

I’ve been using git for source control for a while now, and I’m really enjoying using a distributed system over the conventional server-client system like svn. A distributed versioning system is somewhat conceptually different in the way that is works, and while it’s worth taking the time to understand the differences, one of the immediate differences is in the way branches are stored in the file-system. With a traditional system, checking out a branch of your code involves creating a whole new folder for your local checkout, duplicating a whole lot unnecessarily, though it is pretty obvious what’s going on.

In contrast when you are using git, your local computer has it’s own entire repository (hence distributed), this is stored in a hidden folder inside the project root (myproject/.git/). When you checkout a new branch, the files in the project directory are updated in place with the files from the branch. This means that multiple branches all reside within the same folder on your computer, and only one can be checked out at a time, it can get somewhat confusing at times to remeber which branch is currently checked out, and it’s annoying having to type “git branch” every time you want to find out. Here’s a bash script that displays which git branch is currently checked out whenever your terminal is residing in a git repository.

~/projects/myproject(master) $

Simply add the following code to ~/.bash_profile (create it if it doesn’t exist), and you’ll always know which git branch you currently have checked out.

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* (.*)/(1)/'
PS1="w$(parse_git_branch) $ "