unbound imagination - a blog about programming

Posts tagged with "git"

«

Current Git Branch in Bash Prompt

April 12, 2008

Earlier today, my roommate and I were enjoying our afternoon watching the TextMate for Rails 2 Peepcode and I noticed that in the bash prompt, the current branch was shown in parenthesis. I thought this was a wonderful idea and thought I'd add it to my own bash prompt.

Update: Some much better alternative methods have been posted in the comments, please take a look below.

Here is the code to do it:

   1  export PS1="\[\033[38m\]\u@\h\[\033[01;34m\] \w \[\033[31m\]\`ruby -e \"print (%x{git branch 2> /dev/null}.grep(/^\*/).first || '').gsub(/^\* (.+)$/, '(\1) ')\"\`\[\033[37m\]$\[\033[00m\] "

This will make your bash prompt look like this:

   1  user@hostname currentDirectory (branch name) $

The important part of the PS1 in the first code snippet is this:

   1  # this goes somewhere in your PS1 (it'll make the branch name red)
   2  \[\033[31m\]\`ruby -e \"print (%x{git branch 2> /dev/null}.grep(/^\*/).first || '').gsub(/^\* (.+)$/, '(\1) ')\"\`\[\033[37m\]

I decided to try to do this with sed and not ruby. I came up with this:

   1  export PS1="...\`git branch 2> /dev/null | grep -e ^* | sed -E  s/^\\\\\\\\\*\ \(.+\)$/\(\\\\\\\\\1\)\ /\`\[\033[37m\]$\[\033[00m\] "
   2  # no, your browser is not having rendering issues
   3  # there seriously are that many backslashes

Other than the disgusting backslashes, it's pretty nice. If you use single quotes on the outside instead of double, you can lose a few backslashes:

   1  export PS1='...`git branch 2> /dev/null | grep -e ^* | sed -E  s/^\\\\\*\ \(.+\)$/\(\\\\\1\)\ /`\[\033[37m\]$\[\033[00m\] '