Configuring bash_profile to show git branch returns my branch twice
-
10-02-2021 - |
Question
# show git branch
function parse_git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
function proml {
local BLUE="\[\033[0;34m\]"
local RED="\[\033[0;31m\]"
local LIGHT_RED="\[\033[1;31m\]"
local GREEN="\[\033[0;32m\]"
local LIGHT_GREEN="\[\033[1;32m\]"
local WHITE="\[\033[1;37m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esac
PS1="${TITLEBAR}\
$WHITE\w$GREEN\$(parse_git_branch)$BLUE\
$GREEN\$ "
PS2='> '
PS4='+ '
}
proml
The previous code returns the branch name three times. I just need to see it once...
~/projects/sms(apps2)$
(apps2)
(apps2)
How can I correct this to display just the path + branch?
ie .. ~/projects/sms(apps2)$
Solution
It's the last line of your script that messes up things. Calling proml
directly from ~/.bash_profile
or ~/.bashrc
sets PS*
environment variables only once, so it won't be updated when you change folders (and you might have (apps2)
displayed in every folder you enter later).
Instead, proml
should be set as PROMPT_COMMAND
in last line of your script:
PROMPT_COMMAND=proml
PROMPT_COMMAND
holds the name of the function to be executed each time before bash displays prompt. For more info see here.
Also, speaking of git-aware shell prompts, there's one nice addition to what you already have. Apart from current branch, you can get indication about any uncommitted changes. See e.g. this blog post for parse_git_dirty()
function.
OTHER TIPS
Try changing the last line to PROMPT_COMMAND=proml
;-)