Fixing Git Bash Completion

I didn’t know until yesterday about the __git_ps1 command. You can include it in your bash PS1 like this:

PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

and whenever you’re in a git directory, it will include the current branch in your prompt, along with a few other goodies.

I did this and it didn’t work. It just displayed __git_ps1 in my prompt all the time, which is ugly and not terribly useful.

I couldn’t find an answer on Google, so I ended up just disabling lines in my .bashrc until I could figure out what was wrong. I ended up having to disable this line:

shopt -u promptvars

I don’t know why it was on; perhaps I had a reason for it once and then copied the bashrc from computer to computer, but it’s gone now and my git bash prompt works.

So if you’ve recently heard about __git_ps1 and it’s not working for you, look for the promptvars shopt.

3 Comments

  1. codemac says:

    This is not a command, but a function provided in /etc/bash_completion.d/git

    By unsetting promptvar, prompt strings will not have variable and parameter expansion after being expanded. Which with your simple prompt isn’t an issue, and was probably causing the $() to be expanded earlier than you wanted, meaning the __git_ps1 function wasn’t even being run.

    Anyways, go team git.

  2. Allan says:

    I used to find that bash completion broke to many things so I do not have it enabled anymore. Instead I have this function in my .bashrc:

    git_branch() {
    branch=$(git branch 2> /dev/null | grep “^*” | tr -d “* “)
    [ -n "$branch" ] && printf “(%s)” $branch
    }

    Looking at the __git_ps1 function, it seems to give a lot more information… perhaps I will look into that

  3. Daenyth says:

    You may also be interested in git-sh, which I have in AUR as git-sh-git. It provides a custom prompt with aliases and some other git-based goodies. I find that it makes working with git even more comfortable.