I had my git branch showing in my bash prompt for a long time. I recently changed my code around to make it much faster (more info below). Here are all the steps to go through.
Bash Completion
The first step is to get bash completion installed and install the git files for this as well. I use homebrew on the mac to install most open source stuff so you can just install bash-completion from that:
brew install bash-completion
At the end of the install it tells you to do some things… Do them:
Add the following lines to your ~/.bash_profile file: if [ -f `brew --prefix`/etc/bash_completion ]; then . `brew --prefix`/etc/bash_completion fiTo install Homebrew's own completion script: ln "#{HOMEBREW_PREFIX}/Library/Contributions/brew_bash_completion.sh" "#{etc}/bash_completion.d"
After this you can install git:
brew install git
and it will install the git prompt functions as well. You can try running __git_ps1
from inside a git working directory (in a new shell) to check that it’s working correctly
Adding branch to prompt
If you just want to add the git branch to your prompt you can just use __git_ps1 in your prompt. There’s a lot of details in the git completion file. It’s located at /usr/local/etc/bash_completion.d/git-completion.bash
in a standard install of homebrew.
My prompt
I wanted my branch to change color based on if I’m root or not, if I’m on a remote machine or not and I want the branch color to change based on the git status. I did all this via some really messy shell code before. Recently git added support for some git status information in the git_ps1 output (but not using colors) so I rewrote my code using the same methods they had for determining git status. This was all stuff I could have done before but I’ve never looked into fancy git commands like diff-index and rev-parse before. My current_version of my prompt file is pretty great and ends up much faster.