Thursday, September 1, 2011

Adding Git branch to your command prompt...

It's gotten a bit annoying having to type:

git branch

just to see where I am in my current git repo. So I added the current branch name to my prompt. And, additionally, if I'm not in a git repo then nothing is displayed.

Here's the code from my ~/.bashrc file:

# Setup for my prompt


PS1="$COLOR3\u@\h$COLOR2:$COLOR1\W $COLOR4\$(ruby -e \"print (%x{git branch 2> /dev/null}.grep(/^\*/).first || '').gsub(/^\* (.+)$/, '(\1) ')\") $COLOR1\\$ $COLOR4"

export PS1

The key here is the segment passed into ruby, run in a subprocess. It runs "git branch 2" to find the name of the current branch. If it gets a nil result then it knows we're not in a git repo and it returns an empty string. Otherwise, any result returned is placed within a pair of parantheses.

This give us a nice prompt such as:

mcpierce@mcpierce-laptop:cpp (master)  $

which is very nice. Now I know when I'm on the master branch, my upstream branch or some other branch. No more accidentally forcing a non-fast forwarding commit into the remote repo for me...