Skip to main content
nick.recoil.org
  1. Blog Archive/

Augmenting your shell prompt with Git information

I use git, and from time to time I use the ‘stash’ feature. This is a boon when performing certain tasks, but can also get you into trouble if you don’t carefully manage what you’ve stashed. To this end, I modified my bash shell prompt to help me remember.

Normally my shell prompt gives me fairly standard information. Current working directory, time, hostname and current user.

[nick@20:47:31] dusk : ~/Work
$ 

When I’m inside a git repository, I see something like this.

[nick@20:47:31] dusk : ~/Work/git/MacRuby (master) [2]
$ 

The bracketed ‘master’ shows me what branch I have checked out, and the red ‘2’ shows me that I have two stashed change-sets. This is accomplished by the following bashrc/profile code:

function parse_git_branch {
  ref=$(git symbolic-ref HEAD 2> /dev/null) || return
  echo "("${ref#refs/heads/}")"
}

function parse_git_stash_size {
  lines=$(git stash list -n 100 2> /dev/null) || return
  if [ "${#lines}" -gt 0 ]
  then
    count=$(echo "$lines" | wc -l | sed 's/^[ \t]*//') # strip tabs
    echo "["${count#}"]"
  fi
}

export PS1="[$red\u$NC@$green\t$NC] \h : $cyan\w $yellow\$(parse_git_branch) $RED\$(parse_git_stash_size)\n$NC\$ "

This has been invaluable in helping me keep track of what I’m working on, and helps me make fewer mistakes when managing git repositories.

Nick Ludlam
Author
Nick Ludlam
Creative Technologist