Adding Git Branch to Bash

When working with Git, it’s important to know what branch you’re currently on. Ubuntu doesn’t list the branch by default, so we need to modify Bash in order to display the branch name. Below we will be modifying Bash to display the current branch in parentheses.

Step 1: Edit ~/.bashrc

First we need to modify the .bashrc file in your home directory. Below I will be using nano, but you can replace nano with gedit, vi, emacs, or your favorite editor of choice (maybe vscode or sublime?).

nano ~./bashrc

The code with the # in front of it (the first 6 lines) is the original code you will be looking for. You will add hashes or delete the code as you see fit. I like to comment the code out in case I want to restore the original or in case I make a mistake.

Once you’ve commented out the original lines of code, paste in the lines after the “# Add git branch if its present to PS1” line.

#if [ "$color_prompt" = yes ]; then
#    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
#    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
#unset color_prompt force_color_prompt

# Add git branch if its present to PS1
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w \[\033[01;36m\]$(parse_git_branch)\[\033[0$
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $(parse_git_branch)\$ '

Save the changes and return to your terminal.

If you have a terminal open you can reload the .bashrc without closing it and reopening. Simply use the command “source ~/.bashrc”.

source ~/.bashrc

If you are within a git directory you should now see your terminal look like the image below.

Leave a Reply

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