2

I have a small script named .bash_prompt which is called by source ~/.bash_prompt in ~/.bash_profile.

The script sets my PS1 to display some useful information about the current git repo. Unfortunately the git-part is only being executed when spawning a new terminal, so the branch is only displayed when I call the script manually after changing to a git repo.

How can I make my bash prompt update everytime I execute a command?

function git_branch() {
    local GITDIR=$(git rev-parse --show-toplevel 2>&1)
    if [[ "$GITDIR" != '/Users/\u' ]]
    then
        local BRANCH=`git branch 2> /dev/null | sed -n '/^\*/s/^\* //p'`
      if [ -n "$BRANCH" ]; then
          echo -e "$BRANCH"
      fi
    else
     echo ""
    fi
}

function git_prompt() {
    local prompt_unpushed_symbol="△"
    local prompt_unpulled_symbol="▽"
    local prompt_dirty_symbol="*"
    local prompt_synced_symbol="✓"

    local local_branch=$(git_branch)
    local remote_branch="origin/$local_branch"
    local first_log="$(git log $local_branch $remote_branch -1 2> /dev/null)"

    local STATUS=`git status 2>&1`
    if [[ "$STATUS" == *'Not a git repository'* ]]; then
        echo ""
    elif [[ "$STATUS" != *'working directory clean'* ]]; then
        echo "[$local_branch $prompt_dirty_symbol]"
    elif [[ "$STATUS" == *'Your branch is ahead'* ]]; then
        echo "[$local_branch $prompt_unpushed_symbol]"
    elif [[ -n "$first_log" ]]; then
        echo "[$local_branch $prompt_unpulled_symbol]"
    else
        echo "[$local_branch $prompt_synced_symbol]"
    fi
}

function colorPrompt {
    local c_brace="\[\033[m\]"
    local c_git="\[\033[31m\]"

    local user_host="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h"
    local location="\[\033[33;1m\]\w"
    local tail="\n\$ "

    export PS1="[$user_host $location$c_brace]$c_git$(git_prompt)$c_brace$tail"
}

colorPrompt
strnmn
  • 555
  • 1
  • 6
  • 30
  • Run `declare -p PS1` (or `echo "$PS1"` if `declare -p` doesn't work on OS X for some reason) and look at the value of `PS1` and see if that helps you understand why it doesn't update. – Etan Reisner May 14 '15 at 01:23

1 Answers1

4

The value of the PROMPT_COMMAND shell variable is executed prior to displaying the prompt; one of the main uses of this feature is to set the value of PS1. In your case, all you need to do is add

PROMPT_COMMAND=color_prompt

to your .bash_profile after sourcing .bash_prompt.

chepner
  • 497,756
  • 71
  • 530
  • 681