Show your Current Git Branch in your Shell Prompt

If you’re following good programming practices, you’ll use a reversion control system like git to manage your projects and use branches when adding new features. Jason Seifer has a handy little tip on how to add the active branch into your shell prompt, which works great in Mac OS X’s default bash shell. Just add this to your .profile file in our home directory:

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

export PS1='\[\e[1;37m\][\[\e[1;35m\]\u\[\e[1;37m\]@\[\e[1;32m\]\h\[\e[1;37m\]:\[\e[1;36m\]\w\[\e[1;33m\]$(parse_git_branch)\[\e[1;37m\]]$ \[\e[0m\]'

(Finally had an opportunity to use that SyntaxHighlighter Evolved WordPress plugin.)

Jason likes a lot of colors in his prompt and must not mind it wrapping into the next line, so I’ve muted down the colors and left only the last part of the current working directory in my version:

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

export PS1='\u\[\e[1;37m\]@\[\e[1;32m\]\h\[\e[1;37m\]:\[\e[1;31m\]\W\[\e[1;33m\]$(parse_git_branch)\[\e[0;39m\] '
export PROMPT_COMMAND='echo -ne "\033]0;${PWD}\007"'

As a bonus, I’m even setting the Terminal window title bar with the full current directory path via PROMPT_COMMAND. I’ve also disabled the active process name and dimensions under Terminal’s Settings – Windows preferences, to make room for long paths.

If you want to experiment with other colors, check out this bash prompt color guide for the escape code sequences.

Share this post:
  • Twitter
  • HackerNews
  • Facebook
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Buzz
This entry was posted in Misc and tagged git, shell. Bookmark the permalink.

4 Responses to Show your Current Git Branch in your Shell Prompt

  1. Jason Seifer says:

    Thanks for the link back! I’m giving your prompt a try for a week or so. I’m not sure I’ll stick with it but it sure is concise. The colors work pretty well, too.

    • Joost Schuur says:

      Thanks for the comment. I didn’t want 3 different bright colors pulling my focus away from what I’m most likely going to be typing after the prompt. I figured what mattered most was knowing what folder I was in and what machine I was on (in that order), in case I goof up and run an ‘rm -rf’ where I didn’t want to.

  2. Pingback: Making your $ more informative | Drew Inglis

  3. Pingback: Git – Controle de Versão « Caio's Technology Documentation Blog

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>