Tuesday, April 13, 2010

Adding Git Status Information to your Terminal Prompt

If you're a heavy git user, you'll find this simple prompt customization quite useful. It adds the name of the current branch to the shell prompt along with an asterisk as a dirty indicator. It also displays the number of states you have stashed away with git stash.

Start by defining the following functions and placing it into your shell profile (e.g., .bashrc).
# Returns "*" if the current git branch is dirty.
function parse_git_dirty {
[[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]] && echo "*"
}

# Returns "|shashed:N" where N is the number of stashed states (if any).
function parse_git_stash {
local stash=`expr $(git stash list 2>/dev/null| wc -l)`
if [ "$stash" != "0" ]
then
echo "|stashed:$stash"
fi
}

# Get the current git branch name (if available)
git_prompt() {
local ref=$(git symbolic-ref HEAD 2>/dev/null | cut -d'/' -f3)
if [ "$ref" != "" ]
then
echo "($ref$(parse_git_dirty)$(parse_git_stash)) "
fi
}

Then customize your prompt by adding $(git_prompt) to the PS1 environment variable, for example:
export PS1="\u@\h:\w $(git_prompt)$ "

Here's what my prompt looks like in action:


And, here is the code to my prompt. (It relies on the functions defined above.)
# A fancy colorful prompt
function color_prompt
{
local none="\[\033[0m\]"

local black="\[\033[0;30m\]"
local dark_gray="\[\033[1;30m\]"
local blue="\[\033[0;34m\]"
local light_blue="\[\033[1;34m\]"
local green="\[\033[0;32m\]"
local light_green="\[\033[1;32m\]"
local cyan="\[\033[0;36m\]"
local light_cyan="\[\033[1;36m\]"
local red="\[\033[0;31m\]"
local light_red="\[\033[1;31m\]"
local purple="\[\033[0;35m\]"
local light_purple="\[\033[1;35m\]"
local brown="\[\033[0;33m\]"
local yellow="\[\033[1;33m\]"
local light_gray="\[\033[0;37m\]"
local white="\[\033[1;37m\]"

local current_tty=`tty | sed -e "s/\/dev\/\(.*\)/\1/"`

local u_color=$purple
id -u > /dev/null 2>&1 && #Cross-platform hack.

if [ `id -u` -eq 0 ] ; then
local u_color=$yellow
fi

PS1="$light_blue> $current_tty $u_color\u$brown@${purple}\
\h$brown:$light_blue\w\n$light_blue> $light_red\$\
? $cyan\$(git_prompt)$brown"'\$'"$none "

PS2="$dark_gray>$none "
}

That's all folks! I'm interested in hearing about any useful shell prompt customizations that you have.

5 comments:

  1. zsh has this by default. It also has svn, hg, cvs support.

    ReplyDelete
  2. What would be also useful is the git config "user.name" and "user.mail" settings directly in the shell prompt, because I have many time pushed to a repo with the wrong identity (when working in 2 different environments)

    ReplyDelete
  3. Here is my git prompt for zsh: http://github.com/olivierverdier/zsh-git-prompt

    ReplyDelete
  4. Great stuff.

    You should update this post to include a link to your followup @ http://0xfe.blogspot.com/2010/04/improved-git-enabled-shell-prompt.html

    ReplyDelete