Skip to content

Instantly share code, notes, and snippets.

@eitheror
Created January 6, 2018 01:04
Show Gist options
  • Select an option

  • Save eitheror/974e01048c65f2293e2ee8ee0a96973c to your computer and use it in GitHub Desktop.

Select an option

Save eitheror/974e01048c65f2293e2ee8ee0a96973c to your computer and use it in GitHub Desktop.
Set color bash prompt according to git branch and virtualenv activation.
#!/bin/bash
#
# DESCRIPTION:
#
# Set the bash prompt according to:
# * the branch/status of the current git repository
# * the name of the current virtualenv (if activated)
#
# https://gist.github.com/hugorodgerbrown/4143150/
#
# USAGE:
#
# 1. Save this file as ~/.git_bash_prompt
# 2. Add the following line to the end of your ~/.profile or ~/.bash_profile:
# . ~/.git_bash_prompt
# The various escape codes that we can use to color our prompt.
RED="\[\033[0;31m\]"
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
BLUE="\[\033[0;34m\]"
LIGHT_RED="\[\033[1;31m\]"
LIGHT_GREEN="\[\033[1;32m\]"
WHITE="\[\033[1;37m\]"
LIGHT_GRAY="\[\033[0;37m\]"
COLOR_NONE="\[\e[0m\]"
PROMPT_SYMBOL="\$"
# Detect whether the current directory is a git repository.
function is_git_repository {
git branch > /dev/null 2>&1
}
function set_git_state {
# Set color based on clean/staged/dirty.
if [[ ${git_status} =~ "working tree clean" ]]; then
state="${GREEN}"
elif [[ ${git_status} =~ "Changes to be committed" ]]; then
state="${YELLOW}"
else
state="${RED}"
fi
}
function set_git_remote {
# Set arrow icon based on status against remote.
if [[ ${git_status} =~ "Your branch is ahead of" ]]; then
remote="+"
elif [[ ${git_status} =~ "Your branch is behind" ]]; then
remote="-"
elif [[ ${git_status} =~ "Your branch is up-to-date" ]]; then
remote=""
elif [[ ${git_status} =~ "Your branch and (.*) have diverged" ]]; then
remote="x"
else
remote="?"
fi
}
# Determine the branch/state information for this git repository.
function set_git_status {
# Capture the output of the "git status" command.
if is_git_repository ; then
git_status="$(git status 2> /dev/null)"
set_git_state
set_git_remote
# Set the final branch string.
BRANCH="${state}($(git rev-parse --abbrev-ref HEAD)${remote})${COLOR_NONE}"
else
BRANCH=""
fi
}
# work out if there is a venv activated and set $VENV
function set_venv (){
# Get Virtual Env
if [[ $VIRTUAL_ENV != "" ]]
then
# Strip out the path and just leave the env name
VENV="${YELLOW}[${VIRTUAL_ENV##*/}]${COLOR_NONE}"
else
# In case you don't have one activated
VENV=''
fi
}
function set_history_number () {
HISTORY_NUMBER="${BLUE}\! ${COLOR_NONE}"
}
# Set the full bash prompt.
function set_bash_prompt () {
set_venv
set_git_status
set_history_number
PS1="${VENV} \w ${BRANCH} ${HISTORY_NUMBER}${PROMPT_SYMBOL} "
}
# Tell bash to execute this function just before displaying its prompt.
PROMPT_COMMAND=set_bash_prompt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment