Show current git branch and its status

We’re going to make our bash prompt show the current git branch, with a color indicating its status (green = clean, red = dirty, yellow = clean but not pushed to remote)

The result should be something like this:

current git branch in prompt

Add the following code to your ~/.bashrc

if [ -x /usr/bin/tput ] && tput setaf 1 >& /dev/null; then
	c_git_clean=$(tput setaf 2)
	c_git_dirty=$(tput setaf 1)
	c_git_semi_dirty=$(tput setaf 3)
	c_reset=$(tput sgr0)
else
	c_git_clean=
	c_git_dirty=
	c_reset=
	c_git_semi_dirty=
fi

git_prompt ()
{
	if ! git rev-parse --git-dir > /dev/null 2>&1; then
		return 0
	fi

	git_branch=$(git branch 2> /dev/null | sed -n '/^\*/s/^\* //p')
	if git diff HEAD --quiet 2> /dev/null >&2; then
		git_color="${c_git_clean}"
		dirty=0
	else
		git_color="${c_git_dirty}"
		dirty=1
	fi

	if git diff $git_branch origin/$git_branch --quiet 2> /dev/null >&2; then
		git_color="$git_color"
	else
		if [ dirty=0 ]; then
			git_color="${c_git_semi_dirty}"
		fi
	fi

	echo " ($git_color$git_branch${c_reset})"

}
#the relevant part is $(git_prompt). the following ps will give you a prompt like:
#[username]@hostname [current directory name] (current git branch) $
export PS1='\[\033[0;33m\]\u\[\033[0m\]@\h [\[\033[1;34m\]\W\[\033[0m\]]$(git_prompt) \[\033[0m\] \$ '

Leave a Reply