An Updated Command Prompt

April 12, 2010

It's been a while since I [added the current Git branch to my command prompt](http://barkingiguana.com/2008/11/15/get-the-current-git-branch-in-your-command-prompt) to help with my development workflow. Since then I've started juggling multiple Ruby versions and I find myself increasingly wanting to know the exit status of the last command at a glance. So I gave my prompt an upgrade. Here's what it looks like now: A screen-shot of my command prompt showing username, hostname, exit code of last command, Ruby interpreter information, current working directory and Git information It packs in the username, hostname, last exit code (green for success, red for failure), the active Ruby interpreter and version, the current directory, and Git branch status. Everything I need, nothing I don't. To get this, I declare `$PS1` like so:
# Show the exit code of the last command.
# Idea stolen from @mathie.
function last_exit_code() {
  local code=$?
  if [ $code = 0 ]; then
    printf "$1" $code
  else
    printf "$2" $code
  fi
  return $code
}

# I only want to see the interpreter in the output if I'm not using MRI.
function ruby_version() {
  local i=$(/Users/craig/.rvm/bin/rvm-prompt i)
  case $i in
    ruby) printf "$1" $(/Users/craig/.rvm/bin/rvm-prompt $2) ;;
    *)    printf "$1" $(/Users/craig/.rvm/bin/rvm-prompt $3) ;;
  esac
}

# Show lots of info in the __git_ps1 output.
# Thanks for the info @mathie.
export GIT_PS1_SHOWDIRTYSTATE="true"
export GIT_PS1_SHOWSTASHSTATE="true"
export GIT_PS1_SHOWUNTRACKEDFILES="true"

export PS1='\[\033[01;32m\]\u@\h\[\033[00m\] $(last_exit_code "\[\033[1;32m\]%s\[\033[00m\]" "\[\033[01;31m\]%s\[\033[00m\]") $(ruby_version "\[\033[01;36m\]%s\[\033[00m\]" "v p" "i v p") \[\033[01;34m\]\W\[\033[00m\]$(__git_ps1 "\[\033[01;33m\](%s)\[\033[00m\]")\$ '
A couple of things worth noting. The `last_exit_code` function captures `$?` immediately -- if you wait too long, some other command will overwrite it. And the `ruby_version` function only shows the interpreter name when you're running something other than MRI, which keeps things tidy for the common case. The `GIT_PS1_SHOW*` exports turn on indicators for dirty state, stashed changes, and untracked files in the Git portion of the prompt. If you haven't tried these, they're wonderful -- you'll never accidentally commit from the wrong state again.
Questions or thoughts? Get in touch.