Show Git branch in your terminal
January 12th, 2009
I've seen this around quite a bit on other blogs, but here it is in its simplest form:
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* (.*)/ [\1]/'
}
export PS1='\w $(parse_git_branch) \$ '
Simply add this to .bash_profile/.profile and relaunch your terminal.
This gives me:
~/Sites/curve21/clients/acme/www [master] $
The key part of the PS1 variable is $(parse_git_branch) - you can drop it into your custom prompt if you have one.
6 Responses to “Show Git branch in your terminal”
Sorry, comments are closed for this article.

January 12th, 2009 at 11:27 PM
there's already a helper provided by git.
export PS1='\w[$(_gitps1)] \$ '
January 13th, 2009 at 07:15 AM
You don't need to restart your shell to apply the above change. You should get by by sourcing the file, "source .bashrc". You can also use a single period, ".", if you don't want to type "source".
January 13th, 2009 at 01:14 PM
@bitbit That doesn't seem to work on my machine - perhaps it's a version specific thing - what version are you running?
January 13th, 2009 at 08:30 PM
Hello Steve,
It seems like your script, if it worked, would output multiple []'s. Here is the version that works for me:
parsegitbranch() { git branch 2> /dev/null | sed -e '/^[^]/d' -e 's/ (.*)/ [\1] /' } export PS1='\w$(parsegitbranch)\$ '
January 14th, 2009 at 04:41 PM
@Stephen: http://tinyurl.com/9lckmk
if you are using git.git you should install it manually
(on ubuntu copy it to /etc/bash_completion.d/)
January 14th, 2009 at 10:00 PM
@Ryan - You're right - it does work without the additional [] in the env string. However, I didn't get duplicate [] with them in - weird.
@bitbit On brief scan, that looks pretty cool. I'll check it out - cheers!