Git Branch Name in Your Bash Prompt

By eric

I work with a few repositories at any given time. And during that time, I typically have multiple branches created for each repository. I figured that it would make my life easier if I knew which branch and/or repository I was working in. Luckily, very little hackery is required here since the git distribution already comes with such a tool. (Note: If you didn’t build Git from source, then you may not have this file.)

First thing I did was copy the git auto-completion file into my home directory:

elubow@beacon repo$ cp /usr/local/src/git/contrib/git-completion.bash ~/

Then I edited my .bashrc file to load up my new PS1 variable (PS1 is variable name for the Bash prompt) with git information only if we are currently in a repository. Don’t forget to set a default PS1 in case your .bashrc can’t find your file. Another item of note is that you should have the if state below load after your load your PATH variable. This removes the potential for git having to be located after every commend.

# Set the base PS1
PS1="\u:\h \W$ "

# Source the git bash completion file
if [ -f ~/ ]; then
    source ~/
    PS1='\u@\h$(__git_ps1 " (%s)") \W$ '

export PS1

You’ll notice I also set a variable called GIT_PS1_SHOWDIRTYSTATE. What this variable does is it adds a * to the branch name if the branch has been changed.

There are other options here if you are looking for something more in depth. Git Prompt provides you with a much more in depth version on the command line fo your dirty files and is much more visually oriented.

Additionally, you now get to make use of the other auto-complete features that this script was actually intended for.

elubow@beacon (master*) repo$ git sta
stage    stash    status

Note the difference between my prompt at the beginning of the post and the end. When I am not in a repository, nothing shows in my PS1 variable.

It’s just that simple to do this and definitely saves some time. Enjoy.

Follow My Travels

Buy My Book


  • 2020
  • 2019
  • 2017
  • 2014
  • 2013
  • 2012
  • 2011
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006

New Posts By Email