How to show git branches in terminal

One of the first things I do when setting up a new dev system is activate displaying git branches in the terminal. I find it very practical to know on which branch I’m working on. To show the branch in the console you need to replace the following code in ~/.bashrc:

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

with this:

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;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi

Finally, to activate the functionality you have to call source ~/.bashrc in the terminal: Terminal showing git branch

Source: https://askubuntu.com/questions/730754/how-do-i-show-the-git-branch-with-colours-in-bash-prompt

Published 14 Dec 2019

Remote Developer | Vegan | Pro Wrestling geek | Gamer | Scared of his kids becoming teenagers
Remote Ren on Twitter