Skip to content

Instantly share code, notes, and snippets.

@StevenClontz
Last active September 2, 2020 17:12
Show Gist options
  • Save StevenClontz/ac86f9cb232e5cb916ba80035ffc39e5 to your computer and use it in GitHub Desktop.
Save StevenClontz/ac86f9cb232e5cb916ba80035ffc39e5 to your computer and use it in GitHub Desktop.
Bash Prompt
# set colors for prompt
RED="\[\033[0;31m\]"
YELLOW="\[\033[1;33m\]"
GREEN="\[\033[0;32m\]"
BLUE="\[\033[1;34m\]"
MAGENTA="\[\033[1;35m\]"
LIGHT_RED="\[\033[1;31m\]"
LIGHT_GREEN="\[\033[1;32m\]"
WHITE="\[\033[1;37m\]"
LIGHT_GRAY="\[\033[0;37m\]"
COLOR_NONE="\[\e[0m\]"
# Return the prompt symbol to use, colorized based on the return value of the
# previous command.
function set_prompt_symbol () {
if test $1 -eq 0 ; then
PROMPT_SYMBOL="${LIGHT_GRAY}\$${COLOR_NONE}"
else
PROMPT_SYMBOL="${LIGHT_RED}\$${COLOR_NONE}"
fi
}
# Check if in a pipenv
function set_pipenv_prompt {
if [ -z "$PIPENV_ACTIVE" ]; then
PIPENV=""
else
PIPENV="${GREEN}[pipenv]${COLOR_NONE}"
fi
}
# Detect whether the current directory is a git repository.
function is_git_repository {
git branch > /dev/null 2>&1
}
# Determine the branch/state information for this git repository.
function set_git_branch {
if is_git_repository ; then
# Capture the output of the "git status" command.
git_status="$(git status 2> /dev/null)"
# Set color based on clean/staged/dirty.
if [[ ${git_status} =~ "working tree clean" ]]; then
state=""
elif [[ ${git_status} =~ "Changes to be committed" ]]; then
state="${YELLOW}X${COLOR_NONE}"
else
state="${LIGHT_RED}X${COLOR_NONE}"
fi
# Set arrow icon based on status against remote.
remote=""
remote_ahead_pattern="Your branch is ahead of"
remote_behind_pattern="Your branch is behind"
remote_diverge_pattern="Your branch and (.*) have diverged"
if [[ ${git_status} =~ ${remote_ahead_pattern} ]]; then
remote="${YELLOW}^${COLOR_NONE}"
elif [[ ${git_status} =~ ${remote_behind_pattern} ]]; then
remote="${YELLOW}v${COLOR_NONE}"
elif [[ ${git_status} =~ ${remote_diverge_pattern} ]]; then
remote="${YELLOW}~${COLOR_NONE}"
fi
# Get the name of the branch.
branch_pattern="On branch ([a-zA-Z0-9\_\-\.]*)"
if [[ ${git_status} =~ ${branch_pattern} ]]; then
branch="${MAGENTA}(${BASH_REMATCH[1]})${COLOR_NONE}"
fi
# Set the final branch string.
BRANCH="${branch}${state}${remote}"
else
BRANCH=''
fi
}
function set_bash_prompt () {
set_prompt_symbol $?
set_git_branch
set_pipenv_prompt
export PS1="${YELLOW}\u${BLUE}@\h ${GREEN}\w${COLOR_NONE} ${BRANCH}\n${PIPENV}${PROMPT_SYMBOL} "
}
PROMPT_COMMAND=set_bash_prompt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment