A git-aware prompt

UPDATE: Gitigit in the comment talked about another env var that would show unstaged changes. This article thus contains wrong informations, see the next one to do things properly.

Thanks for pointing me my mistakes Gitigit and Blah! :-)

UPDATE: Blah pointed out in the comments that something already existed, but as I stated, it doesn't quite match my workflow with Git. However, this lead me to think a little and I saw that I didn't understand anything about the difference between staged and unstaged changes :)

After looking at it a bit more, I finally got it, and as such, I updated the below function so that it takes unstaged changes into account.

So once again, thank you blah :-)

I read Peter's post today about how happy he was to have switched to zsh.

Now, this isn't one of those « you're right man, zsh is so much more awesomer » or even « dude, bash can do it too, why did you go to the other side? » posts.

However, Peter had an incredible idea: display the current git branch inyour prompt, as well as whether there are uncommited changes or not.

So I don't really care about what shell I'm using, and bash has at least one huge benefit: it's the default on my distro of choice (and I'm too lazy to change it and learn another one :). But this git thingy, I love it!

Here's what I added to my ~/.bashrc file:

# set the prompt, appending the current git branch (if any)
set_prompt() {
  if [ -d ./.git ]; then
    GITBRANCH="(\[\033[0;32m\]$(awk -F '/' '{ print $NF }' .git/HEAD)\[\033[0m\]"

    if [ $(git diff --exit-code > /dev/null 2>&1; echo $?) -eq 1 ] || [ $(git diff-index --cached --quiet --ignore-submodules HEAD --; echo $?) -eq 1 ]; then

    if [ "x$(git status | grep Untracked)" != "x" ]; then

  echo -ne "\[\033[0;34m\][\u@\h \W]\[\033[0m\]${GITBRANCH}\[\033[0;34m\]\\$\[\033[0m\] "

export PROMPT_COMMAND='PS1="$(set_prompt)"'

This gives me a very nice (and useful!) prompt:

[mathieu@localhost rpmbuild]$

Yeah, not so great... But now let's say I enter a folder which turns out to be a git repository. Name of the current branch appears:

[mathieu@localhost rpmbuild](master--)$

If there are uncommited changes to the tree, then the first green dash after the branch name becomes a red star. Just the same, if there are new untracked files in the tree, the second green dash becomes a red plus.

[mathieu@localhost rpmbuild](master*-)$
[mathieu@localhost rpmbuild](master-+)$
[mathieu@localhost rpmbuild](master*+)$

Hope that can be useful to someone. It certainly is for me :).