Have your bash prompt tell you git information

While you can obviously type in “git status” to see what’s happening (git-wise) in a directory, wouldn’t it be nice if you could automagically see that info?

Well, you can. Just add this snippet to your ~/.bash_profile file:

if [ -f /etc/bash_completion.d/git ]; then
    . /etc/bash_completion.d/git
    PS1='\[\u@\h \e[33m\]\w\[\e[0m\] $(__git_ps1 " (%s)")\n\$ '
fi

Or, if that file doesn’t exist, you can create it with all of this code:

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
if [ -f /etc/bash_completion.d/git ]; then
    . /etc/bash_completion.d/git
    PS1='\[\u@\h \e[33m\]\w\[\e[0m\] $(__git_ps1 " (%s)")\n\$ '
fi

####
#   Stash away examples of other possibilities for the prompt
#####
# PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
# PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$'
# PS1='[\u@\h \W$(__git_ps1 " (%s)")] \[\e[33m\]\w\[\e[0m\]\n\$'

Update!

I tried this on an older server that didn’t have /etc/bash_completion.d on it, and here’s how I got it to work.

1) Downloaded the latest stable version of https://github.com/telemachus/bash_completion.d and copied that directory into /etc/bash_completion.d

2) Created a symbolic link:

ln -s /etc/bash_completion.d/git-completion.bash /etc/bash_completion.d/git

3) If you get this error:

-bash: __git_ps1: command not found

then you will need to add this

if [ -f /etc/bash_completion.d/git-prompt.bash ]; then
   . /etc/bash_completion.d/git-prompt.bash
fi

before the call to . /etc/bash_completion.d/git

Leave a Reply

Your email address will not be published. Required fields are marked *