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
- http://www.linuxnix.com/2013/04/linuxunix-shell-ps1-prompt-explained-in-detail.html
- http://blog.twistedcode.org/2008/03/customizing-your-bash-prompt.html
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:
Written by eranga bandara
Related protips
4 Responses
How to do it with oh-my-zsh :)
https://coderwall.com/p/g801fg?i=11&p=1&q=author%3Aitseranga&t%5B%5D=itseranga
Make sure that you escape the $ at the end of the PS1 line, or it will nuke the colors of your session.
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 ;-)
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