Bash prompt snippets for git, rvm, virtualenv, ssh

Mon, Jun 10 2013 - 2 minute read

The following is just a couple of snippets I have in my bash prompt to identify various environments that I’m in for rvm, git and so on. While you can usually find some way of getting this information in your prompt on the sites of the individual programs, it’s nice to have something where it’s all together. I’ve also tried to make an effort to avoid slow versions of various commands, ideally just parsing environment variables if possible. Each section of the prompt also has the relevant technology prefixed (e.g. git:branchname or rvm:1.9.3@gemset)

Note: My real prompt has several things not mentioned here. For example, I’ve stripped out all colors added to the prompt. The aim of this is to give you a guide to how to quickly get prompt information for git, rvm, virtualenv and so on.

prompt_command() {
    # Runs every time a prompt is displayed

    # Command status - display as red if non-zero
    local BRIGHT=$(tput bold)
    local RED=$(tput setaf 1)
    RETVAL=$?
    if [[ $RETVAL != 0 ]]; then
        RETVAL=$BRIGHT$RED$RETVAL
    fi

    # Git
    GITPROMPT=
    if declare -f __git_ps1 >/dev/null; then
        # Only run if we have the git prompt stuff loaded
        GITPROMPT=`__git_ps1 "%s"`
    fi
    [[ $GITPROMPT == "(unknown)" ]] && GITPROMPT=
    [[ -n $GITPROMPT ]] && GITPROMPT=${PROMPT_MID}git:$GITPROMPT

    # Virtualenv wrapper
    # Note: add 'PS1=$_OLD_VIRTUAL_PS1' to ~/.virtualenvs/postactivate to
    # stop virtualenvwrapper's normal prompt behavior
    VENVPROMPT=
    [[ -n $VIRTUAL_ENV ]] && VENVPROMPT=${PROMPT_MID}venv:${VIRTUAL_ENV##*/}

    # RVM
    RUBYPROMPT=
    local GEMSET=${GEM_HOME#*@}
    if [[ -n $GEMSET && $GEMSET != $GEM_HOME ]]; then
        RUBYPROMPT=${PROMPT_MID}rvm:${RUBYVER}${GEMSET}
    fi
}

setprompt() {
    # Customize these as appropriate
    PROMPT_LEFT='('
    PROMPT_RIGHT=')'
    PROMPT_MID=')-('

    # SSH - shows you what IP you're connecting from
    local SSHPROMPT=${SSH_CLIENT%% *}
    [[ -n $SSHPROMPT ]] && SSHPROMPT="$PROMPT_MID$SSHPROMPT"

    # Set the prompt variable here, customize as appropriate. The
    # important parts are the GITPROMPT, VENVPROMPT and so on. Note that
    # anything set via PROMPT_COMMAND needs to have a backslash before it
    # in order for it to be evaluated every time
    PS1="$PROMPT_LEFT\u@\h$PROMPT_MID\$RETVAL$PROMPT_MID"
    PS1="$PS1\$GITPROMPT\$VENVPROMPT\$RUBYPROMPT$SSHPROMPT$PROMPT_RIGHT"
    PS1="$PS1\n$PROMPT_LEFT\W$PROMPT_RIGHT"
}

PROMPT_COMMAND=prompt_command
setprompt