Snippets

Ben Buchanan BASH: git bling

You are viewing an old version of this snippet. View the current version.
Revised by Ben Buchanan 42da85c
#!/bin/bash

# Usage: source this file in your .bash_profile or .bashrc

# Effect: sets $PS1 to show git branch, dirty and stash status.
# Stash skipped in cygwin as it was too slow when tested, YMMV.

# To insert the git smarts into your own PS1, add this:
# $(git branch &>/dev/null;if [ $? -eq 0 ]; then echo " $(parse_git_branch)$(parse_git_dirty)$(parse_git_stash)"; fi)

# where are we...
case "$(uname -s)" in
  CYGWIN*)    OS="cygwin" ;;
  Darwin*)    OS="osx" ;;
  Linux*)     OS="linux" ;;
  MINGW32*)   OS="windows" ;;
  *)          echo "OS not detected successfully" ;;
esac
# check for WSL (bash-on-ubuntu-on-windows)
# can be removed if you don't need to detect WSL
if [[ $OS = "linux" ]]; then
  if $(grep --silent 'Microsoft' /proc/sys/kernel/osrelease); then
    OS="wsl"
  fi
fi
# end WSL check

if [[ $OS == 'osx' ]];then
  GIT_DIRTY_MESSAGE="nothing to commit, working tree clean"
else
  GIT_DIRTY_MESSAGE="nothing to commit, working directory clean"
fi

parse_git_stash() {
  [[ $(git stash list 2> /dev/null | tail -n1) != "" ]] && echo "^"
}
parse_git_branch() {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1/"
}
parse_git_dirty() {
  [[ $(git status 2> /dev/null | tail -n1) != $GIT_DIRTY_MESSAGE ]] && echo "(*)"
}

if [[ $OS == 'cygwin' ]]
then
  export PS1='\e[1;30m\][\e[\e[1;30m\]\e[1;33m\] \u@\H \[\e[1;32m\]\w\[\e[0m\]$(git branch &>/dev/null;if [ $? -eq 0 ]; then echo " \[\033[01;34m\]\e[1;37m$(parse_git_branch)$(parse_git_dirty)"; fi) \e[1;30m\]] \n$\e[37m\] '
  echo "Cygwin prompt formatting loaded - note no git stash parsing"
else
  export PS1='\[\033[0;37m\][ \[\033[1;33m\]\u@\H \[\033[0;32m\]\w\[\033[0;37m\]$(git branch &>/dev/null;if [ $? -eq 0 ]; then echo " $(parse_git_branch)$(parse_git_dirty)$(parse_git_stash)"; fi) ]\n\$ \[\033[0m\]'  
fi
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.