How to Display the Current git Branch on the Command Line
Share
When you’re using git routinely, it’s helpful to know which branch you’re currently on without having to type git status or git branch.
Fortunately, there’s a convenient way to add your current git branch to your command line prompt. For help with remote branches, check out this guide on how to check out a remote branch.
1 – Open your .bashrc to edit
The .bashrc
file contains many of your bash settings. You can open the file to edit using your command line text editor of choice. The file should be located in your home directory.
vim ~/.bashrc
2 – Add the following to your .bashrc
function parse_git_branch () {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
NO_COLOR="\[\033[0m\]"
PS1="$GREEN\u@\h$NO_COLOR:\w$YELLOW\$(parse_git_branch)$NO_COLOR\$ "
You can add this to the end. Then save and close.
3 – Source your .bashrc
If you’re in a folder with an initialized git repo, you can source your bashrc file and see the difference.
source ~/.bashrc