Bash – Conditional PS1

bashgitprompt

I'm basically trying to make my PS1 look like this when in a git repo:

$ ~/Projects/Blah (master):

Or if I'm not in a Git repo, I want it to look like this:

$ ~/Projects/Blah:

This is my current PS1:

export PS1="$ \w \$(__git_ps1): "

It works for the git repo output, but the problem is that if I'm not in a git repo, the output looks like this:

$ ~/Projects/Blah :

I don't really want that space there if it isn't a git repo, is there some way I can specify this in my PS1?

Best Answer

I ended up using this .git-prompt.sh file. Steps to get this to work:

  1. Create a file called .git-prompt.sh in your home directory (~/.git-prompt.sh) and copy the code from the link above into it.
  2. In your .bash_profile or .bashrc file, add this line: source ~/.git-prompt.sh
  3. Change your PS1 to this: PS1='\n$ \w$(__git_ps1 " (%s)"): '
Related Question