The Pug Automatic

Show Git dirty state (and branch) in the prompt

Written December 3, 2008. Tagged Shell scripting, Git.

I've been using this excellent hack for a while to get the current git branch in my shell prompt.

That takes care of knowing what branch you're on, but I still found myself running git status often after cd:ing into a working directory, to find out if it was dirty (had uncommitted stuff). If it is, I want to handle that before starting on something else.

I hacked that in, and now my prompt looks like e.g.

henrik@Hyperion ~/dev/blog.johannaost.com[master]$

when the working directory is clean, and

henrik@Hyperion ~/dev/blog.johannaost.com[master*]$

when it's dirty – an asterisk is added.

Code for bash, goes into ~/.bashrc:

# http://henrik.nyh.se/2008/12/git-dirty-prompt
# http://www.simplisticcomplexity.com/2008/03/13/show-your-git-branch-name-in-your-prompt/
# username@Machine ~/dev/dir[master]$ # clean working directory
# username@Machine ~/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)]/"
}
export PS1='\u@\h \[\033[1;33m\]\w\[\033[0m\]$(parse_git_branch)$ '
view raw .bashrc hosted with ❤ by GitHub

I have nearly no experience in shell scripting, so please let me know how this can be improved. For one thing, I expect it could be made more efficient by just running git status once and getting both branch and dirtiness from that.

Feel free to contribute versions for other shells.