How to show git branch in bash terminal prompt
by Riley MacDonald, January 9, 2014

While setting up my development environment [Windows 7] for our newest project, I noticed my Cygwin Terminal was not displaying git branches on my bash prompt:

# Actual
Riley /cygdrive/c/users/Riley/Documents/Project-Directory $
# Expected
Riley /cygdrive/c/users/Riley/Documents/Project-Directory (repository-name) $

Since we are working with GitHub and making pull requests, this stuck out as an important feature.
Solution:
Before modifying your existing .bashrc file, it’s a good idea to make a backup copy of it:

# Change Directory to ~
cd ~
# Ensure the .bashrc file exists in this directory
ls -a
# Make a backup copy of the file
cp .bashrc .bashrc-backup
# Open the .bashrc file for editing in notepad [or a editor of your choice :)]
notepad .bashrc

Add the following code at the bottom of the .bashrc file with your editor and save it:

export PS1='\[\033[01;32m\]\h\[\033[01;34m\] \w\[\033[31m\]$(__git_ps1 "(%s)") \[\033[01;34m\]$\[\033[00m\] '

Now apply the change via bash:

# Apply the settings
source .bashrc

Your color scheme should have a noticeable change, along with your git branches displaying inline!

Update! For OS X Users:
For users with terminals such as iTerm2 and a .bash_profile, the following snippet will work:

# Git branch and color variables in bash prompt
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\[\033[01;32m\]\h\[\033[01;34m\] \w\[\033[31m\]\$(parse_git_branch)\[\033[00m\] $ "

Update! For MacOS Catalina (zsh) Users:

For users on MacOS Catalina, which uses zsh, the following snippet will work (credit to https://gist.github.com/reinvanoyen/05bcfe95ca9cb5041a4eafd29309ff29).

function parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
 
COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;243m'
COLOR_DIR=$'\e[38;5;197m'
COLOR_GIT=$'\e[38;5;39m'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n ${COLOR_DIR}%~ ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '
Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

bob on 2017-10-10 20:17:22 said:
this works for me like charm

Riley MacDonald on 2017-09-17 16:36:47 said:
Thanks for the information!

Esteban Serrano on 2017-09-08 15:09:33 said:
Hullo from 2017. I added the "export PS1=..." line to the end of my .bashrc file on cygwin, Windows 10. Unfortunately this was shown at the beginning of each prompt: -bash: __git_ps1: command not found The solution was to save git-prompt.sh to a location (e.g. ~/.git-prompt.sh): wget -O ~/.git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh And then add "source ~/.git-prompt.sh" to .bashrc. :)

J on 2017-03-28 13:40:18 said:
Thanks .. parse_git_branch worked for cygwin

Luke on 2015-09-14 14:30:44 said:
That worked - thanks!