Last Updated: September 07, 2017
· itseranga
892414 10151468467596730 1847316210 o

Add git branch name to bash prompt

In order to add branch name to bash prompt we have to edit the PS1 variable(set value of PS1 in ~/.bash_profile).

What is PS1

PS1 denotes Prompt String 1. It is the one of the prompt available in Linux/UNIX shell. When you open your terminal, it will display the content defined in PS1 variable in your bash prompt

Following is an example bash prompt of my terminal. In here I have defined to display
* user - eranga
* host name of the machine - erangas-MacBook-Pro-4
* current working directory - ~/Workspace/wasn


More details about bash prompt and PS1

Display git branch name

Add following lines to your ~/.bash_profile

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "

In here parse_git_branch() function extract the branch name when your are in git repository. This function output used in PS1 variable in order to prompt the branch name.

In above PS1 we defined following properties
* \u@\h \[\033[32m\] - user, host name and its displaying color
* \w\[\033[33m\] - current working directory and its displaying color
* \$(parse_git_branch)\[\033[00m\] - git branch name and its displaying color

Now when you go to git repository form the terminal it will display currently checked out git branch in the prompt. Following is the example output of bash prompt after adding these changes to ~/.bash_profile


Say Thanks

4 Responses
Add your response


Or you can use oh-my-zsh and stay forever happy with themes. :)

over 1 year ago ·
892414 10151468467596730 1847316210 o
over 1 year ago ·

Make sure that you escape the $ at the end of the PS1 line, or it will nuke the colors of your session.

about 2 months ago ·

Or you can use a helper tool like https://github.com/magicmonty/bash-git-prompt which also shows you the current status of the repository ;-)

7 days ago ·
Filed Under