How to Display the Current git Branch on the Command Line

Tyler Tyler (291)
2 minutes

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.

Posted in these interests:
h/git15 guides
h/unix13 guides

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
Add the following to your .bashrc
function parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
PS1="$GREEN\u@\h$NO_COLOR:\w$YELLOW\$(parse_git_branch)$NO_COLOR\$ "

You can add this to the end. Then save and close.

If you're in a folder with an initialized git repo, you can source your bashrc file and see the difference.

source ~/.bashrc
Tyler Tyler (291)
2 minutes

Sometimes we start writing code without managing our branches in advance. Then we make commits in master (or some other base branch) when we intended to carve off a new feature branch.