Custom Bash Prompt with Git Branch Name
If you often use git
from the terminal, you really should add the current branch to your prompt.
tl;dr
~/.bashrc
|
|
And add $(parse_git)
to PS1 definition(s)
Backstory : bash prompt
The bash shell uses a special variable PS1
that is interpeted everytime bash shows the prompt.
To see what you PS1 is currently:
echo $PS1
For debian buster it is:
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$
Concept: Bash prompt can run commands every time the prompt is shown
You can easily test changes to PS1 just by setting it. This example will set your prompt to the output from the date
commmand. Example:
# prompt with just the date
PS1="$(date) "
Concept: Bash prompts can have colors
Colors are added to bash prompt for ANSI/VT100 with format codes.
echo -e "\033[01;31m\] turn on bright red"
echo -e "\033[00m turn on normal text"
Put it all together
Step 1: Add a command to show the current branch
For the bash prompt, it is easiest just to add a function to your ~/.bashrc file.
I will use git symbolic-ref
“plumbing” command to get the current branch name.
|
|
git symbolic-ref
will avoid the “porcelain” command git branch
which meant to be human readable.
Step 2: Add it to the PS1 command
I prefer to add $(parse_git) the system’s default PS1.
Open ~/.bashrc and change from this:
|
|
to this
|
|
Produces this output: