Reputation: 805
Stupid Saturday morning code snippet.
I've found online a snippet code that allows me to get the current branch in PS1, wonderful! but...
I'd like to have different colors based on the branch.
I said, "You don't know anything about bash but should be really easy! just an if..."
After 6 hours of tests, here we go.
Could someone explain me where is the problem?
I know that there are many projects on GitHub that do this job for me, but I would like just to understand.
Thank you so much
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
set_ps1_git_branch_color(){
BRANCH=$(parse_git_branch)
if [ $BRANCH == "(master)" ]; then
echo -e "\W\[\033[35m\] $BRANCH \[\033[00m\]"
fi
if [ $BRANCH == "(test)" ]; then
echo -e "\W\[\033[32m\] $BRANCH \[\033[00m\]"
fi
}
export PS1="\u@\h $(set_ps1_git_branch_color) $ "
It works just if I execute source ~/.bash_profile
after each git operations ( like checkout ).
But the original snippet parse_git_branch()
is able to change the branch name without the source command.
so...what I'm missing here? :(
Upvotes: 2
Views: 297
Reputation: 805
Just in case someone is interested.
This script show the branch in PS1, if the branch is 'master' the name will be red and blinking if the branch is 'test' the name will be yellow and blinking. For others branches, the colour will be white.
# Output colors
red='\033[31;5m';
white='\033[0;97m';
yellow='\033[33;5m';
default='\033[0;m';
blue='\033[0;34m';
magenta='\033[0;35m';
cyan='\033[0;36m';
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
set_ps1_git_branch_color(){
BRANCH=$(parse_git_branch)
if [ -z $BRANCH ]; then
return 0
fi
if [ $BRANCH = "(master)" ]; then
echo -e "${red}${BRANCH}${default}"
return 0
fi
if [ $BRANCH = "(test)" ]; then
echo -e "${yellow}${BRANCH}${default}"
return 0
fi
echo -e "${white}${BRANCH}${default}"
}
export PS1="${cyan}\h ${magenta}\u ${blue}\w\$(set_ps1_git_branch_color)${default} \n\\$ \[$(tput sgr0)\]"
Thank you so much CodeWizard! :)
Upvotes: 2
Reputation: 142024
export PS1="\u@\h $(set_ps1_git_branch_color) $ "
# should be (added \ before $(set...))
# the \ will execute the command during runtime and not right now.
# without the \ it will executed and determined of first run and not every time
export PS1="\u@\h \$(set_ps1_git_branch_color) $ "
# Output colors
red='\033[0;31m';
green='\033[0;32m';
yellow='\033[0;33m';
default='\033[0;m';
set_ps1_git_branch_color(){
...
echo -e "${green} $BRANCH ${default}"
}
# Output colors
red='\033[0;31m';
green='\033[0;32m';
yellow='\033[0;33m';
default='\033[0;m';
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
set_ps1_git_branch_color(){
BRANCH=$(parse_git_branch)
if [ $BRANCH == "(master)" ]; then
echo -e "${green} $BRANCH ${default}"
fi
if [ $BRANCH == "(test)" ]; then
echo -e "${yellow} $BRANCH ${default}"
fi
}
export PS1="\u@\h \$(set_ps1_git_branch_color) $ "
Upvotes: 3