Wednesday, April 29, 2009

Git Branch on the command prompt

It is sometimes very useful to know the git branch you are working on right from the command prompt. You can do this by editing the ~/.bashrc file.



This will show up a prompt which looks like this and fails gracefully when you are not on a git repo.


vagmi@deepthought:~/work/testproj[master]$ git checkout new_feature
Switched to branch "new_feature"
vagmi@deepthought:~/work/testproj[new_feature]$ cd ..
vagmi@deepthought:~/work$


This saves a lot of "git branch" when you are coding.

6 comments:

Anonymous said...

the stuff in your pre tag didn't come in the google reader.. and i banged my head for couple of seconds.. wonder if the github thing is worth it

Unknown said...

May be I should just post the code snippet directly on the blog instead of putting it as a gist. But the gist formatting is so pretty. :-)

Dhruva Sagar said...

Well it works absolutely fine!

Anonymous said...

Ah, nice idea, thanks.

I added it to my "setup my coding environment" script, using this line:

export PS1=`echo "$PS1"|sed -r s/\(.*\\w\)\(.*\)/\\\\1\$\(bash_git_branch\)\\\\2/`

Anonymous said...

Nice idea, but invoking python on each prompt is a bit overkill, here's a lighter implementation:

git branch 2>/dev/null | sed -ne 's/^\* \(.*\)//p'

Anonymous said...

How about awk?

function bash_git_branch
{
git branch 2> /dev/null | grep \* | awk '{print $2}'
}