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.

2 comments:

  1. Below is a PS1 optimization takes things a bit further - showing repository name, branch name, and state (dirty/clean) all within your prompt: https://gist.github.com/3848872

    btw the tab completion is great, thanks - combined with the PS1 I use, the git command line experience is pretty incredible.

    ReplyDelete
  2. seems that one also needs to download & source git-prompt.sh

    ReplyDelete