Skip to content

Instantly share code, notes, and snippets.

@rbarbey
Last active October 19, 2015 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rbarbey/120e4d254daeb3884e95 to your computer and use it in GitHub Desktop.
Save rbarbey/120e4d254daeb3884e95 to your computer and use it in GitHub Desktop.
Git bash prompt
function git_prompt {
# get the current status in short notation
local status=$(git status -sb 2> /dev/null)
# if we don't get any output, we're not in a git repo
if [ -z "$status" ]; then
return
fi
# determine color for displaying the branch name
# default=no changes; yellow=merge; red=untracked/modified; green=added
local color="\e[39m"
if [ ! -z "$(egrep '^UU' <<< "$status")" ];then
color="\e[33m"
elif [ ! -z "$(egrep '^[^#][^ ]' <<< "$status")" ]; then
color="\e[31m"
elif [ ! -z "$(egrep '^[MARCD]' <<< "$status")" ]; then
color="\e[32m"
fi
# get name of the branch and ahead/behind info
local status_line=$(head -1 <<< "$status")
local branch=$(sed -e "s/^## \([^\.]*\).*/\1/" <<< "$status_line")
local ahead=$(sed -e "/.*ahead \([0-9][0-9]*\).*$/!d;s//\1/" <<< "$status_line")
if [ -z "$ahead" ]; then
ahead="0"
fi
local behind=$(sed -e "/.*behind \(.*\)]/!d;s//\1/" <<< "$status_line")
if [ -z "$behind" ]; then
behind="0"
fi
# e.g. [develop 1↑5↓]
echo -e " [$color$branch\e[0m $ahead\u2191$behind\u2193] "
}
export PS1='\u@\h:\w$(git_prompt)$ '
@domizei385
Copy link

Cool stuff. On Mac I am using the following script. It does not include the ahead/behind state, but it should work for Mac in case Roberts script does not:

alias git='LANG=en_US git'
export PS1='\[$(tput setf 2)\]\u\[\033[0;31m\] \W \[$(tput setf 3)\]`GIT_BRANCH=$(git branch 2>/dev/null | cut -f2 -d* -s | sed "s/^\ //"); ([[ -n $GIT_BRANCH ]] && echo -n "\[\033[0;33m\][git:\[\033[1;33m\]$GIT_BRANCH]\[\033[0m\]")`\$'

@rbarbey
Copy link
Author

rbarbey commented May 15, 2014

Thanks for that. My script above was written on a Mac with macports and bash 4.3 installed. I think the \e directives are only working on bash 4.x.

@rbarbey
Copy link
Author

rbarbey commented Oct 19, 2015

Now deprecated. Use magicmonty/bash-git-prompt if you can.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment