ZSH Prompt to show git branch

February 15, 2008

After using git for a little bit I started tinkering with ZSH, to get the current branch in my prompt. What I ended up with is this:

Turns out it's pretty easy - somewhere in your .zshrc you need to put the following:

# get the name of the branch we are on
git_prompt_info() {
  ref=$(git-symbolic-ref HEAD 2> /dev/null) || return
  echo "(${ref#refs/heads/})"
}
autoload -U colors
colors
setopt prompt_subst
PROMPT='%{$fg_bold[green]%}%n@%m %{$fg[blue]%}%c %{$fg_bold[red]%}$(git_prompt_info)%{$fg[blue]%} %% %{$reset_color%}'

The git_prompt_info function just asks git what branch we are in (and returns if we're not in a git repo), and then strips out regs/heads from the output. The colors bit is just so you can use colors like green instead of this awesomeness. prompt_subst is needed to tell zsh we want the git_prompt_info substituted with it's results, otherwise it will just show it as a string.

Thats pretty much it! I initially had a right hand prompt for the branch, which while looks nicer, makes it less likely to be seen... My original prompt looked like this:

PROMPT='%{$fg_bold[green]%}%m %{$fg[blue]%}%c %% %{$reset_color%}'
RPROMPT='%{$fg_bold[yellow]%}$(git_prompt_info)%{$reset_color%}'
1 Roy van der Meij: April 3, 2008

Nice one!
I think I'll implement this later this day.
I still have to move all projects to git though.

Add comment

About

I'm a programmer and shutterbug living on the West Coast of Canada.

Blog Archive

Recently Heard

A Liberal Educationby New Model ArmyPlayed on 2008/07/16 at 02:35PM
The Two Sides of Monsieur Valentineby SpoonPlayed on 2008/07/16 at 02:32PM
You Weren't Thereby New Model ArmyPlayed on 2008/07/16 at 02:28PM
Powered by Viviti