Executing commands in PS1 on macOS Sierra not working

bashgitterminal

Recently I had to switch to a Mac for my work. Since I'm used to Unix-like environments, I brought over my PS1 prompt generator from Ubuntu.

I had enough trouble customizing the terminal for it to look somewhat usable (who thought that black letters on white background are an okay solution in 2017?). However one thing won't work…

Namely, the git ps1 extension. Yes, I installed the bash-completion and git packages via Homebrew, and sourced both the git-completion.bash and git-prompt.sh before assigning PS1.

My .bash_profile looks like this:

build_prompt () {
  clear="\[$(tput sgr0)\]"
  blue="\[\033[38;5;27m\]"
  green="\[\033[38;5;2m\]"
  yellow="\[\033[38;5;11m\]"

  export PS1="[${blue}\u${clear}@${green}\h${clear}] ${yellow}\w${clear}$(__git_ps1 " (%s)") \\$ > "
} 


source /usr/local/etc/bash_completion.d/git-completion.bash
source /usr/local/etc/bash_completion.d/git-prompt.sh

export GIT_PS1_SHOWDIRTYSTATE=yes
export GIT_PS1_SHOWCOLORHINTS=true
export CLICOLOR=1

alias ls='ls -GFhAl'
build_prompt

As you can see I add the __git_ps1 to the end of my PS1 value, and in theory it should display Git tree info whenever in a git repo folder.

However this script is only ran once, when bash starts up. The same code however works on Ubuntu just fine, dynamically displaying git tree info no matter where I start bash. On this Mac, however, it only displays the value it picks up on launch, so if I start a bash prompt in a git folder, I'll be stuck with its info display until I close the terminal instance.

What am I doing wrong here?

Best Answer

With a minimal test case (minus, of course, the frivolous colors) it appears that the quoting of PS1 is important:

gitfoo () {
    echo >&2 "was run"
    git status -bs 2>/dev/null | head -1
}
#PS1="x$(gitfoo)x "
PS1='x$(gitfoo)x '