Bash prompt with Git branch and status

Tuesday, 13 April 2010 by alexandrul
Permalink

Based on Gunnar Wolf’s .bashrc, I have customized my .bash_profile to show exit status, bare repositories, and outside work tree cases:

git_prompt_bare_repo.png

git_prompt_normal_repo.png

git_prompt_outside_work_tree.png

#
# term colors
	
txtrst="\033[0m"     # reset
	
# regular colors
txtK="\033[0;30m"    # black
txtR="\033[0;31m"    # red
txtG="\033[0;32m"    # green
txtY="\033[0;33m"    # yellow
txtB="\033[0;34m"    # blue
txtM="\033[0;35m"    # magenta
txtC="\033[0;36m"    # cyan
txtW="\033[0;37m"    # white
	
# emphasized colors
emK="\033[1;30m"
emR="\033[1;31m"
emG="\033[1;32m"
emY="\033[1;33m"
emB="\033[1;34m"
emM="\033[1;35m"
emC="\033[1;36m"
emW="\033[1;37m"
	
# background colors
bgK="\033[40m"
bgR="\033[41m"
bgG="\033[42m"
bgY="\033[43m"
bgB="\033[44m"
bgM="\033[45m"
bgC="\033[46m"
bgW="\033[47m"
	
#
# aliases
	
alias less='less -r'
# --show-control-chars: help showing Korean or accented characters
alias ls='ls -F --color --show-control-chars'
alias ll='ls -al'
	
#
# branch info
	
parse_git_branch() {
	
	branch=`git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* (.*)/1/'`;
	
	# ? valid branch
	if [ ! -z "$branch" ];
		then
	
			# ? bare repo
			if [ x`git config core.bare`x == "xtruex" ];
				then
					branch="${branch}${txtrst} (bare)";
	
				else
					gitstatus=`git status 2>&1`;
	
					# ? outside work tree
					if echo "${gitstatus}" | grep -i 'must be run in a work tree' &> /dev/null;
						then
							branch="${branch}${txtrst} (outside work tree)";
	
					# ? modifications
					elif ! echo "${gitstatus}" |grep 'nothing to commit .working directory clean' 2>&1 > /dev/null;
						then
							branch="${branch}${emY}*";
							new=$(( `git ls-files -o --exclude-standard|wc -l` ));
							del=$(( `git ls-files -d --exclude-standard|wc -l` ));
							mod=$(( `git ls-files -m --exclude-standard|wc -l` - ${del} ));
							#let "mod = ${mod} - ${del}"
							if [ $del != 0 ]; then branch="${branch}${emR} ${del}d"; fi;
							if [ $mod != 0 ]; then branch="${branch}${emY} ${mod}m"; fi;
							if [ $new != 0 ]; then branch="${branch}${emC} ${new}n"; fi;
					fi;
	
			fi;
	
	fi;
	
	echo -ne "${branch}";
	
}
	
#
# exit status
	
PROMPT_COMMAND='RET=$?;';
	
parse_return_value() {
	
	ret_value="${txtrst}$RET";
	
	if [[ $RET = 0 ]];
		then
			echo -ne "${ret_value}${txtG} ;)";
		else
			echo -ne "${ret_value}${emR} :(";
	fi;
	
}
	
#
# custom prompt
	
# PS1='[\033]0;$MSYSTEM:w\007
# \033[32m]u@h [\033[33mw $(parse_git_branch)\033[0m]
# $ '
	
TITLE_BAR="[\033]0;w - u@h using $MSYSTEM\007]";
	
PS1="$TITLE_BARn  $(parse_return_value)${txtY} w${emG} $(parse_git_branch)${txtrst}n$ ";
	

You can download the archived code here: bash_profile.zip

Add comment

Fill out the form below to add your own comments

User data





Add your comment