Last Updated: November 03, 2021
· itseranga

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


Related protips:

Remove all your local git branches but keep master

4 Responses
Add your response

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

over 1 year ago ·

Or you can use a helper tool like which also shows you the current status of the repository ;-)

over 1 year ago ·

Just wanted to point that colors actually go before what you want to color :
[\033[32m]\w is what makes the working directory \w green

over 1 year ago ·