Displaying git branch info in your bash prompt

Posted on 09. Aug, 2011 by in Techniques & Tricks

We have a lot of distributed work going on across they Hydra community.  All of this work is coordinated with git using a Git branching workflow that requires you to do all development of new features in feature-specific branches.   Juggling git branches within a single project can be confusing enough, but doing it across many projects made it essential to have my command prompt always tell me which branch I’m on.

A quick search turned up two useful posts on the topic:

Bedazzle your bash prompt with git info
Current Git Branch in Bash Prompt

I also ended up digging around in the documentation about color hashes in bash.  Now that’s some seriously ugly configuration code.

I set up my prompt to look like this:

~/Develop/projects/hydra-head (rails3) :

Here’s how I did it:

All I had to do was put these lines in ~/.profile


export PS1="$BLACKw $CYAN`ruby -e "print (%x{git branch 2> /dev/null}.grep(/^*/).first || '').gsub(/^* (.+)$/, '(1) ')"`$GREY:[33[00m] "

I’ve included the color-hash variables for everyone’s sanity.


One Response to “Displaying git branch info in your bash prompt”

  1. matt 13 January 2012 at 6:42 pm #

    Update: Grep works differently in Ruby 1.9, meaning that this will cause an error like `

    ‘: undefined method `grep’ for
    “”:String (NoMethodError)

    Update 26-01-2012: Updated this with a better (but still ugly) fix.

    %x{git branch 2> /dev/null}.grep(/^*/).first

    You have to call .split on strings before calling grep on them. Here’s an ugly but functional replacement that works in 1.9

    branch = %x{git branch 2> /dev/null}; branch.empty? ? nil : print(branch.split[branch.split.index('*')+1])

    Full line for .profile:

    export PS1="$BLACK\w $CYAN\`ruby -e \"branch = %x{git branch 2> /dev/null}; branch.empty? ? nil : print(branch.split[branch.split.index('*')+1])\"\`$GREY:\[\033[00m\] "

Leave a Reply

You must be logged in to post a comment.