MrYoshiji
MrYoshiji

Reputation: 54902

Special color for "master" git branch name in bash prompt

I have the following in my ~/.bashrc which make my prompt display (branch_name) $ in green when I am in a directory using Git.

Example:

yoshi@x1carbon:~ $ cd /path/to/git/project
yoshi@x1carbon:/path/to/git/project (master) $
#                                   ^^^^^^^^ this part only in green

What I want is to display the branch name in yellow instead of green only if I am on master.

This is what I currently have:

git_branch() {
  branch=$(__git_ps1 2> /dev/null)
  if [ "$branch" = " (master)" ]; then
     echo "\[\033[33m\]\${branch}\[\033[00m\]" # yellow
  elif [ "$branch" = "" ]; then
     echo "\[\033[31m\] (no git)\[\033[00m\]" # red
  else
     echo "\[\033[32m\]\${branch}\[\033[00m\]" # green
  fi
}
export PS1="\u@\h:\w$(git_branch) \$ "

The problem is it always display (no git), even if __git_ps1 in the directory returns the proper current branch name. It seems that $branch is always equal to an empty string, whether I am in a dir using git or not.

The following works but applies the same color for all branch names:

git_branch_simple() {
  echo "\[\033[33m\]\$(__git_ps1 2> /dev/null)\[\033[00m\]"
}
export PS1="\u@\h:\w$(git_branch_simple) \$ "

What am I missing here? How can I store the result of __git_ps1 in a local variable and then test it?


Edit: Thanks to @ElpieKay, I identified the different problems I had in my script:

Upvotes: 1

Views: 1085

Answers (1)

ElpieKay
ElpieKay

Reputation: 30976

Try this snippet

git_branch() {
  branch=$(__git_ps1 2> /dev/null)
  if [ "$branch" = " (master)" ]; then
     echo -e "\033[33m${branch}\033[00m" # yellow
  elif [ "$branch" = "" ]; then
     echo -e "\033[31m (no git)\033[00m" # red
  else
     echo -e "\033[32m${branch}\033[00m" # green
  fi
}
PS1='\u@\h:\w`git_branch` \$ '

Upvotes: 3

Related Questions