Git branch in bash prompt

I never seem to know what branch of a repository I’m on, and typing git branch gets tiresome. I found a neat trick to print the name of the current branch at the end of your shell prompt (if the current directory is not a git repository, then it’s just blank). The site I found this on (HalloweenBash) contains a lot of customizations, this is just one that I found useful.

First copy this short function into your .bashrc file:

function parse_git_branch {
   git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

Then in your PS1 variable (which sets the prompt), put \$(parse_git_branch) where you want the branch name to appear. My full prompt looks like this:

PS1="\[\033[G\]\[\e]0;\w\a\]\n\[\e[32m\]\u \[\e[33m\]\w \[\e[36m\]\$(parse_git_branch)\[\e[0m\]\n\$ "

…but I confess to not knowing exactly what all the escape sequences do. The basics are, \u is your username, \h is the hostname (which I removed), and \w is the working directory. This PS1 makes a prompt that looks like this:

Picture1

If you’re curious, you can check out my full .bashrc file here.

Advertisements

2 thoughts on “Git branch in bash prompt

  1. Pingback: Water Programming Blog Guide (Part 2) – Water Programming: A Collaborative Research Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s