Bash – display GIT in prompt when current directory has a .git folder

bashgitprompt

Can I display GIT in prompt when current directory has/contains a .git folder? Is there a way to do this? My current prompt is defined like so:

export PS1="[\u@\h] \w $ "

So, my prompt looks like this:

[user@computer] ~/workspace  $

And I want it to dynamically look like this:

[user@computer] ~/workspace GIT $

Best Answer

The most standard way is to use __git_ps1 directly from git. In Ubuntu, it is available in this path:

source /usr/lib/git-core/git-sh-prompt
## source /etc/bash_completion.d/git-prompt
#PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $(__git_ps1 "(%s)")\$ '

You can notice the added part $(__git_ps1 "(%s)"), which will notify you about the current state of repo -- current branch, ongoing rebases, merges and so on.

The file in Ubuntu is provided by git package:

$ dpkg-query -S /usr/lib/git-core/git-sh-prompt
git: /usr/lib/git-core/git-sh-prompt

For fedora by git-core (with a bit different path):

rpm -qf /usr/share/git-core/contrib/completion/git-prompt.sh
git-core-2.5.5-1.fc23.x86_64

Your prompt will change from

[user@computer] ~/workspace $ 

to

[user@computer] ~/workspace (master)$ 
Related Question