• 0

How to always display your active git branch in the bash prompt

When working on git, it can sometimes get annoying to have to run git status to check which branch you are currently on. You can avoid yourself those extra keystrokes and be a bit more productive if you can set your shell prompt to always show you the active branch name. You can do the following.

Ubuntu

Create a file anywhere in your file system and add the following lines to it. For simplicity sake, I will create the file ~/bash_prompt_git_branch.
parse_git_branch() {

    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'

}

export PS1="\u@\h \W\[33[32m\]\$(parse_git_branch)\[33[00m\] $ "
Then, simply open your ~/.bashrc file and add this to the end of the file
$ source ~/bash_prompt_git_branch
Open a new terminal and traverse to a new directory to view the changes, or, just do source ~/bash_prompt_git_branch for the changes to reflect in the current terminal.

Mac/OSX

Create a new file called ~/.bash_profile if it not already exists
touch ~/.bash_profile
Add the lines
parse_git_branch() {

    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'

}

export PS1="\u@\h \W\[33[32m\]\$(parse_git_branch)\[33[00m\] $ "
Then run the following command in your terminal session to enable the setting.
$ source ~/.bash_profile
There's probably a way to make this setting more persistent on a Mac. If you know what it is, let me know in a comment and I will update the post.