2

Could anyone explain why the branch name is not showing up on my (bash) prompt?
I am using ubuntu 16.10. I tried to use the instructions from this site.

# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

My .bashrc file is here: https://github.com/JeremieGauthier/.bashrc/blob/master/.bashrc

I also tried the following code but it didn't work either.

function color_my_prompt {
    local __user_and_host="\[\033[01;32m\]\u@\h"
    local __cur_location="\[\033[01;34m\]\w"
    local __git_branch_color="\[\033[31m\]"
    #local __git_branch="\`ruby -e \"print (%x{git branch 2> /dev/null}.grep(/^\*/).first || '').gsub(/^\* (.+)$/, '(\1) ')\"\`"
    local __git_branch='`git branch 2> /dev/null | grep -e ^* | sed -E  s/^\\\\\*\ \(.+\)$/\(\\\\\1\)\ /`'
    local __prompt_tail="\[\033[35m\]$"
    local __last_color="\[\033[00m\]"
    export PS1="$__user_and_host $__cur_location $__git_branch_color$__git_branch$__prompt_tail$__last_color "
}
color_my_prompt
TT--
  • 2,956
  • 1
  • 27
  • 46
  • 2
    Rather than `git branch` (which is a porcelain command), you should use `get rev-parse --abbrev-ref HEAD` to get the branch name. And if you stop discarding the error message you may see that perhaps you are not in a git working directory, so `parse_git_branch` generates no output. – William Pursell Aug 30 '17 at 19:45

1 Answers1

2

At installation git comes with a git-prompt.sh that a bash function __git_ps1 to update the prompt.

The function is simple and add the current branch when you cd inside a git repo directory.

Just add a call to this function or another one available in your ps1 and make sure your .bashrc or your .bash_profile load the bash_completion directory.

If your version of git doesn't include the git_prompt.sh script, manually download it and follow the instructions it provide.

lee-pai-long
  • 2,147
  • 17
  • 18