Get the Current Git Branch in Your Command Prompt

November 15, 2008

It seems like everyone and their dog has their own way to show the current Git branch in the command prompt. Here's mine. Drop this into your ~/.profile:

export PS1='\[\033[01;32m\]\u@\h\[\033[00m\] \[\033[01;34m\]\w\[\033[00m\]$(git branch &>/dev/null; if [ $? -eq 0 ]; then echo "\[\033[01;33m\]($(git branch | grep ^*|sed s/\*\ //))\[\033[00m\]"; fi)$ '

The result looks like this:

craig@shiny ~/sandbox/addressbook(master)$

Now with 50% cleaner code

Shortly after posting this, I discovered that Git ships with an auto-completion file that includes a handy __git_ps1 function. If you enable Git auto-completion, you can get the same prompt with much less noise -- and pick up some useful tab-completion goodies along the way:

export PS1='\[\033[01;32m\]\u@\h\[\033[00m\] \[\033[01;34m\]\w\[\033[00m\]$(__git_ps1 "\[\033[01;33m\](%s)\[\033[00m\]")$ '
Questions or thoughts? Get in touch.