Search code examples
gitbashpromptps1

Conditional space in PS1


I'm basically trying to create a PS1 that has this output:

$ ~/Projects/Blah (master):

However, if the folder I'm in is not a Git repository, I want it to look like this instead:

$ ~/Projects/Blah:

This is my current PS1:

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

It gives me the output I want for when I'm in a Git repo, but when I'm in a folder that is 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?


Solution

  • 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)"): '