How to show current git branch with colours in Bash prompt on Ubuntu 20.04

Photo by Bram Naus on Unsplash

How to show current git branch with colours in Bash prompt on Ubuntu 20.04

Problem statement:

If you're using Ubuntu 20.04 for your day-to-day work, at the first launch of VSCode editor you can find that your integrated terminal doesn't show any branch name. Typing every time git branch command to show your current branch name is not an option. Thankfully there is a way to solve this.

Solution:

To show the branch name on your bash terminal, you can add the following code snippet into your .bashrc file:

# Show git branch name 
force_color_prompt=yes  
color_prompt=yes  
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  
unset color_prompt force_color_prompt

After adding the code and saving the changes, you need to reload your .bashrc file with the following command:
$ source ~/.bashrc

Explanation:

bashrc file is a script file that's executed when a user logs in. The file itself contains a series of configurations for the terminal session. This includes setting up or enabling: coloring, completion, shell history, command aliases, and more. It is a hidden file and simple ls command won't show the file. [Source]

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts. source is a shell built-in in Bash and other popular shells used in Linux and UNIX operating systems. [Source]