Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ozydingo
Last active August 15, 2020 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozydingo/98a84a20da937c81b99a4d5b216b1603 to your computer and use it in GitHub Desktop.
Save ozydingo/98a84a20da937c81b99a4d5b216b1603 to your computer and use it in GitHub Desktop.
Display your git branch and status in your terminal
# To use gitbranch to set your prompt to include a colored git branch label:
# bash:
# source .gitbranch
# bash_colors
# PS1='[\[$(git_branch_color)\]$(parse_git_branch)\[${NORMAL}\]] '"$PS1"
# zsh:
# source .gitbranch
# zsh_colors
# setopt PROMPT_SUBST
# export PROMPT='[%F{$(git_branch_color)}$(parse_git_branch)%f] %B%F{240}%~%f %# '
bash_colors() {
export BLACK=$(tput setaf 0)
export RED=$(tput setaf 1)
export GREEN=$(tput setaf 2)
export YELLOW=$(tput setaf 3)
export BLUE=$(tput setaf 4)
export MAGENTA=$(tput setaf 5)
export CYAN=$(tput setaf 6)
export WHITE=$(tput setaf 7)
export NORMAL=$(tput sgr0)
}
zsh_colors() {
export BLACK='black'
export RED='red'
export GREEN='green'
export YELLOW='yellow'
export BLUE='blue'
export MAGENTA='magenta'
export CYAN='cyan'
export WHITE='white'
export NORMAL='default'
}
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
gitver='none'
fi
echo -e $gitver
}
git_branch_status () {
if ! git rev-parse --git-dir >/dev/null 2>&1 ; then
echo none
return 0
fi
firstline=1
gitstatus=clean
while read line; do
if [ $firstline -eq 1 ]; then
# Read first line to determine if we are ahead or behind remote
firstline=0
if [[ $line =~ '\[ahead .+\]' ]]; then gitstatus=ahead; fi
if [[ $line =~ '\[.*behind .+\]' ]]; then gitstatus=behind; fi
else
# Read sceond line: anything here means there's a modified or added file
[ -n "$line" ] && gitstatus=dirty
fi
done < <(git status -sb | head -2)
echo -ne $gitstatus
}
git_branch_color () {
case "$(git_branch_status)" in
dirty)
echo "$RED"
;;
ahead)
echo "$CYAN"
;;
behind)
echo "$YELLOW"
;;
clean)
echo "$GREEN"
;;
none)
echo "$NORMAL"
;;
*)
echo "$NORMAL"
echo ".gitbranch error: unrecognized status $(git_branch_status)" >&2
;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment