Thursday, December 18, 2008

Git your branch name into your shell

I use git on my Ubuntu for my Rails projects, and very frequently I need to know what branch I'm working on right now.
If I can just get my shell to display the current local branch all the time in the prompt, it'd be a lot easier. I just found I could do so.

You need to modify the environment variable PS1 to show your current local git branch.

For me, it looks like this now.

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w [$(git branch 2>/dev/null| grep "\*" | cut -f 2 -d " ")]\$ '

And it renders out like

kazim@invincible:~/projects/aprioriate [refactoring]$


In short, you need to append the following to the PS1 string.

[$(git branch 2>/dev/null| grep "\*" | cut -f 2 -d " ")]\$


The redirection of stderr to /dev/null is required since it suppresses git error messages in case you're not inside a git directory.

Ugly though it may be, it works. And to make the PS1 persist, add the line into your ~/.bashrc file.

PS: I use bash. For zsh and others, its even easier to do this.

1 comment:

Waseem said...

To make it more fancy I will append following in my PS1 string.

[\[\033[32;40m\]$(gi t branch 2>/dev/null|grep "\*" | cut -f 2 -d " ")\[\033[00m\]]\$

It will make the name of the branch green. For more see this.