Skip to content

Instantly share code, notes, and snippets.

@fiee
Created November 7, 2013 04:57
Show Gist options
  • Save fiee/7349180 to your computer and use it in GitHub Desktop.
Save fiee/7349180 to your computer and use it in GitHub Desktop.
Colored bash prompt with git information (tested on OSX 10.9)
# for ANSI color codes see e.g. http://bitmote.com/index.php?post/2012/11/19/Using-ANSI-Color-Codes-to-Colorize-Your-Bash-Prompt-on-Linux
parse_exit_code() {
# check exit code and display a green checkmark on "0" or a red cross with exit code on error
if [ "$?" == "0" ]; then
echo -e "\033[32m✓\033[00m"
else
echo -e "\033[1;31m❌ $?\033[00m"
fi
}
parse_user() {
# check if the user is root, then display "#", else "$"
if [ ${EUID} -eq 0 ]; then echo '#'; else echo '$'; fi
}
parse_git_status() {
# if the current path is a git repository, display "±"; red if changed, green if clean
local STATUS=`git status 2>&1`
if [[ "$STATUS" != *'Not a git repository'* ]]; then
if [[ "$STATUS" == *'working directory clean'* ]]; then
echo -e "\033[0;32m±\033[00m"
else
echo -e "\033[0;31m±\033[00m"
fi
fi
}
parse_git_branch() {
# display current git branch, if any; * if ???, # if ???, + if changed
in_wd="$(git rev-parse --is-inside-work-tree 2>/dev/null)" || return
test "$in_wd" = true || return
state=''
git update-index --refresh -q >/dev/null # avoid false positives with diff-index
if git rev-parse --verify HEAD >/dev/null 2>&1; then
git diff-index HEAD --quiet 2>/dev/null || state='*'
else
state='#'
fi
(
d="$(git rev-parse --show-cdup)" &&
cd "$d" &&
test -z "$(git ls-files --others --exclude-standard .)"
) >/dev/null 2>&1 || state="${state}+"
branch="$(git symbolic-ref HEAD 2>/dev/null)"
test -z "$branch" && branch='<detached-HEAD>'
echo -e "\033[37m${branch#refs/heads/} ${state}\033[00m"
}
# use bracket quoting for color codes, otherwise readline miscalculates line length
PS1='$(parse_exit_code) $(parse_git_status) $(parse_git_branch)\n\[\033[1;32m\]\u@\h\[\033[00m\]:\[\033[1;34m\]\w\[\033[00m\] $(parse_user) '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment