Show current Git branch name in command prompt

If you are working with git via command line, almost everyone would have faced a need to know the current working branch at times. There are numerous ways in which you can show the current git branch.

git branch // Shows all the local branches of your repo. The starred branch is your current branch.
git rev-parse --abbrev-ref HEAD // Shows current branch

There are other tools like Zsh and OhMyZsh

While searching around i found a simple way by editing .bashrc file.

The following code shows the current branch appended to the command prompt:

#Adds git branch details if available in command line
function parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
RED="\[\033[0;31m\]"
BLUE="\[\033[0;34m\]"
GREEN="\[\033[0;32m\]"
YELLOW="\[\033[0;33m\]"
NO_COLOR="\[\033[0m\]"
PS1="$GREEN\u@\h$NO_COLOR:\w$BLUE\$(parse_git_branch)$NO_COLOR\$ "

1

Cheers

1 Comment on "Show current Git branch name in command prompt"


  1. fantastic,thanks,
    Once you add above code to .bashrc, you need to reload it, using following command on terminal,

    source ~/.bashrc

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *