Did you know that you can navigate the posts by swiping left and right?

How to show current git branch with colours in Terminal/Bash prompt

24 Aug 2021 . category: Tech . Comments
#linux #ubuntu #tutorial

Terminal showing git branch in file path

Knowing the git branch you are currently working on helps you avoid the crucial mistake of coding in the wrong branch which may have numerous repercussions. They may be reversible but it just adds more work.

How do you keep track of the branch you are working on? You may choose to keep the branch you are working on in memory or verify with a git command each time. Is that really efficient? I guess your answer is ‘No’.

So in this article I am going to teach you how to show the branch you are working on in the terminal by editing your .bashrc file.


TL;DR

To show the branch name in your terminal replace this code in your .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\$ '

With the following code:


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)\$ '


Step by step guide

1 - To make this change, open the ~/.bashrc configuration file which is found in your home directory.

2 - In the .bashrc window hit ‘CTRL + F’ and search for PS1. The code that is going to be replaced starts from line 59 and ends at 62 in the image below.

Searching for PS1

3 - You may choose to replace the code block or comment them out and paste the new code below the existing one as done in the image below.

Adding new code to file

4 - Save and close the .bashrc file and restart your terminal to see the change.

Alternatively, you can run this command to reload the terminal:

source ~/.bashrc

Conclusion

Final result

Finally you can see the branch you are working on whenever you navigate to a git repository in your terminal.

References


Me

Samuel Darkwah Manu is an awesome person.