Bash – Git PS1 Branch Based Coloring

A few coworkers have asked me why I didn’t have Git setup on my Mac so that when I am in a repository it will show which branch. I finally set that up and did a little extra inside of my ~/.bash_profile. The following lines were added to get everything working:

# has the definition of __git_ps1 and the other auto-completion stuff
. ~/git-completion.bash

# sets up the bash prompt so that when I am in a branch, it will indicate which branch
function set_bash_prompt {
    # Colors found at https://wiki.archlinux.org/index.php/Color_Bash_Prompt
    local branch=$(__git_ps1 "%s");
    if [[ "$branch" == "master" ]] 
    then
        PS1='\[\e[1;31m\]\[\e[4;31m\]'"$branch"'\[\e[0m\]';
    elif [[ "$branch" != "" ]]
    then
        PS1='\[\e[1;34m\]\[\e[4;34m\]'"$branch"'\[\e[0m\]';
    else
        PS1='\u';
    fi
    PS1='\n\[\e[4;30m\]local(\!)\[\e[0m\]:\W '$PS1'\$ '
}

# Tell bash to execute this function just before displaying its prompt.
PROMPT_COMMAND=set_bash_prompt

After sourcing my ~/.bash_profile file, now whenever I am in the master branch, the word “master” appears underlined in red at the end of the prompt. If I am not in the master branch but am in a directory in the repository, the name of the branch will appear underlined in blue. In all other cases, the prompt will appear normal. The following are screenshots showing what I am talking about:

Informative Command Prompt with Git

Informative Command Prompt with Git

Final Notes

  1. One of the cool things I learned while setting this pu was the fact that you could assign a function to PROMPT_COMMAND to make that function run before the command prompt returns control to the user.
  2. Another cool thing that I kind of re-learned was about coloring portions of the command prompt.
  3. Go here if you are looking for a good reference for formatting your Bash command prompt the way that you want.

Leave a Reply

Your email address will not be published. Required fields are marked *


8 × seven =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">