Show Git dirty state (and branch) in the prompt
Written December 03, 2008 at 18:57 CET. Tagged Shell scripting and 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:
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)$ '
Also available as a gist, if you want to fork it.
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.
