'git' Branch Displayed by 'bash' Prompt

It is easily possible to let e.g. the bash command line prompt display the name of the current branch, if the working directory is a git repo.

For example, if my-project is a git repo and I'm just working on the my-cool-feature branch, the command prompt may look like:

martin@pc-martin  ~/projects/my-project (my-cool-feature)
$ 


The following lines can be used to set the command line prompt accordingly:

# Configure a bash prompt that shows the branch name
# if the directory is part of a git repo.
# Stolen from the 'git for Windows' package.
export PS1='\[\033]0;$TITLEPREFIX:$PWD\007\]\n\[\033[32m\]\u@\h \[\033[35m\]$MSYSTEM \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n$ '


These lines can be added to a bash configuration file, e.g.


Putting a file into the /etc/profile.d/ directory may not work, especially on Debian/Ubuntu, because apparently the files in that directory are read too early, and the shell prompt is set later, and overriding the shell prompt discussed here.


A workaround for Debian/Ubuntu-based systems is to edit the file /etc/bash.bashrc and add the line

test -s /etc/bash.bashrc.local && . /etc/bash.bashrc.local

at the bottom of that file.


The function __git_ps1, which actually does the work, is part of the git-completion files that are usually included in the git core software distribution, and installed e.g. as /etc/bash_completion.d/git-prompt.sh.

So the files and thus the __git_ps1 function should be available on every system that has a current version of the git software package installed.


See also:


Martin Burnicki martin.burnicki@burnicki.net, last updated 2022-05-11