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”

  1. bitbit Says:

    there's already a helper provided by git.

    export PS1='\w[$(_gitps1)] \$ '

  2. Nolan Eakins Says:

    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".

  3. Stephen Bartholomew Says:

    @bitbit That doesn't seem to work on my machine - perhaps it's a version specific thing - what version are you running?

  4. Ryan Mulligan Says:

    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)\$ '

  5. bitbit Says:

    @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/)

  6. Stephen Bartholomew Says:

    @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!

Sorry, comments are closed for this article.