Puppet: System Administration Automated

Git branch in your bash prompt


Kevin Barnes has posted his mechanism for getting the current branch of the git repository into his bash prompt.

He mentions color in his article, and it turns out I'm the person who added the color, so I figured I'd post my version.

Here are the functions I have:

git_current_branch()
{
  git branch 2>/dev/null | sed -n '/^\*/ s/^\* //p'
}

git_display()
{
  br=$(git_current_branch)
  if [ -n br ]; then
      echo $br | BRANCH="$br" GIT_COLOR=$(git_color) awk '{if ($1) { print ENVIRON["GIT_COLOR"] ENVIRON["BRANCH"] " " } }'
  fi
}

git_color()
{
    git status 2>/dev/null | grep -c : | awk '{if ($1 > 0) { print ENVIRON["ORANGE"] } else { print ENVIRON["PINK"] } }'
}

And then here's my prompt:

title="033]0;h:W007" PS1="$title[$(git_display)$GREENw$NOCOLOR]nu@h("'$?'") $ "

First, the git bits. As Kevin mentions, I color the branch name; I use orange if I've got modified files, and pink if I don't (these are names that I map elsewhere to terminal codes). The three functions provide the three, um, functions: See what branch I'm on, see whether there are uncommitted files, and colorize the branch name.

Now, the bash bits.

First, you'll notice I have a multi-line prompt. I first started this when I switched to a color prompt, because for a while there bash didn't like the hidden characters that add color. I got to choose between a multi-line prompt, or a prompt that wrapped in broken ways. Since I really only wanted color in the path, I put that on the upper line, avoiding most of the wrapping problems. It was worth it, because (especially when I was still a sysadmin by trade) having color, almost any color, in the prompt makes it easy to pick out my commands from command output.

Now that I've had my prompt this way for about 4 years, I'm pretty fond of it. I think the bash wrapping problems are mostly fixed now, but I'm keepin git.

The $title sets the terminal title (which is slightly useful).

So, that's how I add the git branch, colored by whether I have uncommitted files, to my prompt, with a bit more prompt info thrown in for kicks.

add to del.icio.us Add to Blinkslist add to furl Digg it add to ma.gnolia Stumble It! add to simpy seed the vine TailRank post to facebook

Mon, 05 May 2008 | Tags: , ,


Posted by enendyReurne at Thu May 8 00:02:40 2008
favorited this one, guy

Posted by Jean-Baptiste Quenot at Thu May 15 18:13:06 2008
That's a great tip!  However to avoid issues with color and line-wrapping I'd suggest to use zsh instead of bash.  It works soooo much better!  And you gain many other features as bonus.

Name:


E-mail:


URL:


Comment: