Display current git branch in bash

      No Comments on Display current git branch in bash

Sometimes it’s very useful to know which git branch you are working on right from the command prompt. There are many solutions out there, but most of them include python and some awk or grep magic which can time a serious amount of time when you cd into a reasonably large git tree.

But you can also take advantage of the __git_ps1 function, provided by /etc/bash_completion.d/git in the git package. Add this line to ~/.bashrc:

export PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

This setting helps you keep track of which branch you are in at a given time. If you are in a git working directory, it shows the current branch as part of the prompt:

[user@host directory-name (master)]$ 

If you do not have the bash-completion package installed, you must manually source the git completion script prior to using __git_ps1(). To do this, add

source /etc/bash_completion.d/git

to ~/.bashrc.

You might also want to display when there are changes in your work tree or the git index:

[user@host directory-name (master*)]$ 
[user@host directory-name (master+)]$ 
[user@host directory-name (master%)]$ 
  • * indicates that a tracked file was modified
  • + indicates that a tracked file was modified and staged (with git add)
  • % indicates that you have untracked files in your tree

To do so, simply add these lines in your ~/.bashrc, right before the line modifying your prompt:


See the comments at the beginning of /etc/bash_completion.d/git for more details.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.