Skip to content


Bash Prompt for RVM and Git

I’ve seen a lot of examples where people have a cool Bash prompt showing their Ruby version, RVM gemset, and/or their Git branch.

What I couldn’t find is a complete example that helped me understand what was going on and worked properly on OS X.

Here’s what I did, and maybe you’ll find it useful.

ESC="\033" # This is the escape sequence
NO_COLOR="$ESC[0m"
IRED="$ESC[1;31m" # ANSI color code for intense/bold red
IGRN="$ESC[1;32m" # ANSI color code for intense/bold green
 
# From http://railstips.org/blog/archives/2009/02/02/bedazzle-your-bash-prompt-with-git-info/
# I had to change 'git-symbolic-ref' to 'git symbolic-ref'
function parse_git_branch {
  ref=$(git symbolic-ref HEAD 2> /dev/null) || return
  echo " ["${ref#refs/heads/}"]" # I wanted my branch wrapped in [], use () or <> or whatever
}
 
# from http://ariejan.net/2010/04/25/ruby-version-and-gemset-in-your-bash-prompt-yes-sir
function rvm_version {
  local gemset=$(echo $GEM_HOME | awk -F'@' '{print $2}')
  [ "$gemset" != "" ] && gemset="@$gemset"
  local version=$(echo $MY_RUBY_HOME | awk -F'-' '{print $2}')
  [ "$version" != "" ] && version="$version"
  local full="$version$gemset"
  [ "$full" != "" ] && echo "${full}:" # the colon at the end is a delimiter, you could use a space instead
}
 
#PS1="\h:\W \u\$" # For reference, here's the default OS X prompt
#export PS1="\$(rvm_version)\W \$(parse_git_branch)\$ " # Without the colors
 
# I had to put the \[ and \] down here, as opposed to $IRED, to avoid wrapping funkiness.
export PS1="\[$IRED\]\$(rvm_version)\[$NO_COLOR\]\W\[$IGRN\]\$(parse_git_branch)\[$NO_COLOR\] \$ "

I encountered all kinds of weirdness getting the colors to work. The problems all centered around getting the \[ and \] correct. If you’re having problems where the wrapping is wrong, or arrow keys or the backspace causes your prompt to disappear, check your \[\]‘s. The rule of thumb is the characters you’re escaping should be wrapped in them. Keep in mind, the color codes don’t seem to include a ] at the end.

I got my color codes from here. At the bottom of that page is a dandy script which prints out all the colors and backgrounds making it easy to find a good color combination for your terminal.

References:
Ruby version and gemset in your Bash prompt? Yes sir!
Bedazzle Your Bash Prompt with Git Info

Posted in Bash, Git, OS X, Ruby.

Tagged with , , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.