harperville
harperville

Reputation: 7639

I'm required to manually source ~/.bashrc to display and update GIT branch in my command prompt

When I log into my CentOS server, my ~/.bashrc file is being sourced. This is evident because 1.) I have a logger "sourcing ~/.bashrc" message in ~/.bash_profile and I see that message in /var/log/messages; and 2.) My prompt does show my current working directory, one of many things that are unique to my prompt.

However, when I cd into a Git repo, the current Git branch isn't being displayed:

(/home/jenkins/GitLab/testing-scripts/tests) jenkins-tests $

While I'm in this repo, if I source my ~/.bashrc file, I see my Git branch as I would have anticipated:

(/home/jenkins/GitLab/testing-scripts/tests) jenkins-tests  $ . ~/.bashrc
(/home/jenkins/GitLab/testing-scripts/tests) jenkins-tests (devel)$

If I chance my branch, in order to get the current branch to be displayed, I have to source ~/.bashrc again.

My ~/.bashrc executes the common __git_ps1 command sourced from here.

My ~/.bash_profile contains the following:

GP=~/.git-prompt.sh
if [ -f $GP ]; then
  . $GP;
  logger "sourced $GP";
fi
BRC=~/.bashrc
if [ -f $BRC ]; then
  . $BRC;
  logger "sourced $BRC";
fi
BA=~/.bash_aliases
if [ -f $BA ]; then
  . $BA;
  logger "sourced $BA";
fi

My ~/.bashrc is very long (colors and aliases, etc) but there are only two PS1 lines, one for root and one for not root.

if [ $(id -u) -ne 0 ];
then                            # You are not root
  export PS1="${BLUE}(${RED}\w${BLUE}) ${NORMAL}\h ${undgrn}$(__git_ps1) ${RED}\$ ${NORMAL}"
else
  export PS1="${RED}\u${BLUE}(${RED}\w${BLUE}) ${NORMAL}\h ${RED}\$ ${NORMAL}"
fi

Notice how the rest of my prompt is formatted correctly and updates when I change working directories...but Git branch does not unless I source ~/.bashrc again (a.k.a. every time).

From everything else I've seen, the only other thing I can think of is sourcing /etc/bash_completion, which I am doing very early in my ~/.bashrc file. The fact that the prompt displays the Git branch ought to indicate that functionally, everything is as it should be, I would think.

Stumped.

Any suggestions?

Upvotes: 1

Views: 678

Answers (1)

Vampire
Vampire

Reputation: 38639

You evaluate the content of PS1 at evaluation time of .bashrc. This means of course it is not updated if the branch changes or anything.

You want to set the PROMPT_COMMAND instead. This is evaluated each time the prompt is shown. In there you have to evaluate the current value for PS1 and set it. Then the display is always up to date.

Upvotes: 7

Related Questions