Tuesday, October 4, 2011

Git bash prompts and tab completion

Someone recently asked me about my nifty bash command-prompt with git branch names. If I'm not in a git directory, then the bash prompt looks normal:

[clalance@localhost ~]$

However, as soon as I cd into any directory that is a git repository, my prompt changes:

[clalance@localhost oz (master)]$

If I'm in the middle of a rebase, my prompt looks like:

[clalance@localhost oz (master|REBASE-i)]$

There are many other prompts, but that just gives you a taste of what you get. All of this goodness is due to the git-completion file that is shipped along with the git sources. The canonical place for git-completion.sh is actually the upstream git sources; you can see it here: http://repo.or.cz/w/git.git/blob/HEAD:/contrib/completion/git-completion.bash. Basically, you download that file, put it somewhere in your home directory (mine is at ~/.git-completion.sh), source it from your .bashrc, and then modify your PS1 to call the appropriate function. The end of my .bashrc looks like:

source ~/.git-completion.sh
export PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

The additional benefit that you get from sourcing .git-completion.sh is that you get branch auto-completion, which is also a very useful feature.