Last Updated: February 25, 2016
·
715
· cristeab

openSUSE bash shell for showing git branch status

I have found extremely useful to display at the bash shell the git branch status instead of using
git branch
git diff HEAD

Here is my implementation for openSUSE bash shell (put all these lines into your .bashrc)

c_red=`tput setaf 1`
c_green=`tput setaf 2`
c_sgr0=`tput sgr0`

parse_git_branch ()
{
  if git rev-parse --git-dir >/dev/null 2>&1
  then
    gitver=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
  else
    return 0
  fi
  echo -e " [$gitver]"
}

branch_color ()
{
  if git rev-parse --git-dir >/dev/null 2>&1
  then
    color=""
    if git diff --quiet HEAD 2>/dev/null >&2 
    then
      color="${c_green}"
    else
      color=${c_red}
    fi
  else
    return 0
  fi
  echo -ne $color
}

PS1='\u@\h:\w\[$(branch_color)\]$(parse_git_branch)\[${c_sgr0}\]> '

When a change is present either in your working copy or in your git index, the branch name is colored in red, otherwise the color is green (I am assuming that you use the terminal profile with green text on black background).