2

I am using fedora OS and I want to display git branch or tag in terminal when I go into the git folder project.

I follow this tutorial. After I ran:

source /usr/share/git-core/contrib/completion/git-prompt.sh
source ~/.bashrc

It displays the git branch well. But if I run:

cd .. #I go back the parent folder which is not git folder

It keeps the git branch. How can I fix it?

  • This is strange. Can you show more details on your directories structures and the prompt diplsayed? After your change in .bashrc did you log out and in again ? – Patrick Mevzek Mar 18 '18 at 19:02
  • I've just read /usr/share/git-core/contrib/completion/git-prompt.sh. Instruction about how enable this feature placed at the begin of file. Also, after instruction about enabling this feature the sentence "# The argument to __git_ps1 will be displayed only if you are currently # in a git repository." is present. It's mean that feature must work right. Please try enable feature again following instructions in git-prompt.sh. – Yurij Goncharuk Mar 18 '18 at 19:24
  • @GAVD: Did you set GIT_PROMPT_ONLY_IN_REPO to1 before sourcing? – user1934428 Mar 19 '18 at 10:18
  • you have a .git directory in parent directory, don't you? – Lara Maia Oct 3 '18 at 9:21
0

Not sure about how the tutorial is misbehaving, but you can do this yourself pretty easily. Define an alias like this in your .bashrc:

# function for PS1 to display [ git branch] when it is defined
function __show_git_branch() {
  branch=`git rev-parse --abbrev-ref HEAD 2>/dev/null`
  test -n "$branch" && echo " [$branch]"
}

then set PS1 to something like this:

PS1='-- $(__show_git_branch) \$ '

This will cause the git branch to be recalculated every time the prompt is displayed. If there is an error, it is sent to /dev/null and the subsequent test will not echo anything, so that this will return an empty string if you are not in a git directory.

You did not ask this, but I pass it along as a "handy hint." It can be helpful to know that you are re-initializing everything when playing with bash aliases and environment variables. A straightforward way of doing this is to use exec:

exec bash

This will re-start bash over the currently running shell. If you want to restart it as if you were logging in again, then exec bash -l.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.