Showing the current git branch in the Bash prompt

This is just a simple explanation of how I hacked my BASH prompt to show me the current Git branch of my current working directory.

Having done one too many git svn rebase commands while on the wrong Git branch, I started looking for a way to always know which branch I'm working on. What better place to do this than hacking it into my BASH prompt?

Lo and behold, there in the PROMPTING section of the bash(1) man page (or this page) is my answer: "...After the string is decoded, it is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal...".

From my ~/.bashrc:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u\[\033[01;37m\]@\[\033[00;30;43m\]\h\[\033[00m\] \$ '
export PS1="\e[1;37m[\w]\e[1;34m\`$HOME/scripts/prompt_add.sh\`\e[00m\n$PS1"

The bold bit is the only important bit for the issue at hand. It simply replaces the bold text with the output of the script it runs. A very important thing to note is that the back ticks are escaped (thanks to Joshua Price's blog post about BASH prompt hacking for showing how this should be handled). Without escaping the back ticks, the prompt_add.sh is only run once when ~/.bashrc is read (login time).

All that's left is the prompt_add.sh script itself:
#!/bin/bash

if [ -n "$(git status 2>&1 | grep -v '^fatal: Not a git repository')" ]; then
echo \[git: $(git branch | grep '\*' | awk '{ print $2 }')\]
fi

Probably not the nicest way to determine the Git branch, but it works.

Come to thing of it, you can add any code to that script that you would want in your prompt. Hmmm... what else can I jam in there? >:)