Last Updated: December 03, 2019
·
373
· pwpearson

Colorized Command Prompt Git Branch and Status

Add to .bashrc or .bash_profile in order to get colorized git branch status.

When using CLI and cd'd into a git folder the prompt will look like the following:

me@MBP:[~/OneDrive/electronics/nixie-voltmeter] (master)
$

The current git branch is displayed between the '( )'.
When there are Untracked files or files ready to be staged the branch name is RED.
When there are staged files ready to be committed the branch name is YELLOW.
When there are no changes the branch name will be GREEN.

[ "$TERM" = "xterm" ] && TERM= "xterm-256color"

RED="\[\033[0;31m\]"
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
BLUE="\[\033[1;34m\]"
NO_COLOUR="\[\033[0m\]"
CYAN="\[\033[0;36m\]"
PURPLE="\[\033[0;35m\]"

function parse_git_branch () {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

function set_git_branch () {
  # 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
        B_STATE="${GREEN}"
    elif [[ ${git_status} =~ .*"Changes to be committed".* ]]; then
        B_STATE="${YELLOW}"
    else
        B_STATE="${RED}"
    fi
}

prompt_cmd () {
    set_git_branch
    PS1="$NO_COLOUR\n\u@\h:[\w]${B_STATE}\$(parse_git_branch)$NO_COLOUR\n\$ "
}

PROMPT_COMMAND="prompt_cmd"

Screen Shot 2019-12-01 at 1.01.43 PM.png