Change bash prompt to include git or mercurial branch and dirty indicator

Thanks to my colleague @huugsy and Henrik Nuy. With some additions to include the same information for Mercurial.

Include the snippet below in your /etc/bash.bashrc file:

# http://henrik.nyh.se/2008/12/git-dirty-prompt
# http://www.simplisticcomplexity.com/2008/03/13/show-your-git-branch-name-in-your-prompt/
# Mercurial additions see http://blog.progs.be/?p=351
#
# joachim likes it like this:
# joachim:~/dev/dir[master]$ # clean working directory 
# joachim:~/dev/dir[master⚡]$ # dirty working directory
 
function parse_git_dirty {
  [[ $(git status 2> /dev/null | tail -n1) != "nothing to commit, working directory clean" ]] && echo "⚡"
}
function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/[\1$(parse_git_dirty)]/"
}
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
 
function parse_hg_dirty {
  [[ $( hg status 2> /dev/null ) != "" ]] && echo "⚡"
}
function parse_hg_branch {
  hg branch 2> /dev/null | sed -e "s/\(.*\)/[\1$(parse_hg_dirty)]/"
}
 
 
export PS1='\u:\[\033[1;33m\]\w\[\033[0m\]$(parse_git_branch)$(parse_hg_branch)$ '

Do make sure you .gitignore or .hgignore file is complete or you will always see the dirty thunderbolt.

4 Comments

  1. balder says:

    Nice! Although I don’t need it anymore. I’m using zsh (ZShell) with zsh-git-prompt ( http://github.com/olivierverdier/zsh-git-prompt )
    Zsh and Bash are very similar, but zsh is more flexible.

  2. joachim says:

    Depending on your bash/terminal settings, it may actually be good to also put this at the and of ~.bash_aliases (or both).

  3. joachim says:

    I updated the post to work with the latest git. For older git versions, you will need to replace the “nothing to commit, working directory clean” bit in the script by “nothing to commit (working directory clean)”.

  4. Joachim says:

    Voor de nieuwste git versies moet je “working tree clean” zetten ipv “working directory clean”

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen

*