Show actual git branch in prompt

To show the actual git branch of a project when you are in bash put the following function into your profile (e.g. .bash_profile):

get_git_branch() {
  local br=$(git branch 2> /dev/null | grep "*" | sed 's/* //g')
  [ -n "$br" ] && echo " @$br"
}

and set your prompt accordingly:

export PS1='\\u@\\h:\\w$(get_git_branch) \\$ '

(Replace double-slashes above with single-slashes!)

For example, go into a project and see the shell prompt expands with the actual branch:

rbe@rbemac3:~ $ cd project/odisee/
rbe@rbemac3:~/project/odisee @master $

Create a new branch:

rbe@rbemac3:~/project/odisee @master $ git branch -a
* master
  remotes/github/master
  remotes/origin/master
rbe@rbemac3:~/project/odisee @master $ git checkout -b rel2
M   grootils
Switched to a new branch 'rel2'

And again, the prompt changed:

rbe@rbemac3:~/project/odisee @rel2 $

HTH.

Ralf Bensmann

Ralf Bensmann

Software Architect, Trainer, Author
Java Standard and Enterprise Edition
Clojure, Groovy & Grails
OpenOffice, LibreOffice

Archive

2012 (3)
2011 (43)
2010 (34)
Posterous theme by Cory Watilo