Displaying the current Git branch in my Linux terminal prompt
It wasn't until I heard about a cool, fast, new, insert-superlative-here terminal that I began thinking about how nice it would be to have the active Git branch displayed in the terminal at all times. Because this was a feature of the cool, fast, new, etc. terminal I decided to install it... and was promptly hit with a login page. Excuse me? I need an account registered on someone else's site to use a terminal installed on my computer?
As it turns out, getting and displaying the current Git branch is easy peasy if you can stomach a little bash scripting.
Step one, have Git installed and be on a relatively recent version. I currently have 2.34.1 installed, and the latest release, as of this writing, is 2.44.0.
Step two, open ~/.bashrc
in your text editor of choice. I'm a vim girl, so
vim ~/.bashrc
Step three, add a line that begins with PS1=
that will contain whatever information you want in the terminal prompt. This is where things start to get a little bit technical.
This is a very simple prompt, showing the current directory, the Git branch, and a dollar sign.
PS1="\w\$(__git_ps1)\$ "
However, I like things to be colorful and interesting, so I've added some colors and an emoji.
PS1="💀 \[\033[01;36m\]\w\[\033[01;33m\]\$(__git_ps1)\[\033[01;32m\]\$\[\033[00m\] "
To break it down:
\[\033[01;36m\]
is a blue color in the terminal. \w
is the current directory. \[\033[01;33m\]
is a yellow color in my terminal. \$(__git_ps1)
appends the current Git branch. The $ is important, without it, the branch name won't update when you change branches. \[\033[01;32m\]
is a green color, \$
prints a dollar sign, and \[\033[00m\]
returns the text following the prompt back to white, unbolded text.
Step four, save and exit out of your text editor.
Step five, type the following into your terminal:
source ~/.bashrc
The terminal should change to reflect your new settings.
I know just enough about .bashrc and bash scripting to be dangerous, so take care while following these steps, and maybe also look up some other resources if you get stuck. Here's one from the actual Git docs: Git in Other Environments - Git in Bash. These are the steps that worked for me on a Pop!_OS system, so if you're on an Ubuntu flavor of Linux, I think this will work for you too.