Add VC “branch” to your prompt

Inspired by a recent discussion on IRC, here’s another little piece of bash script goodness. This one goes in your startup files, and it integrates with your $PS1 prompt variable. The script adds your VC branch to the prompt. I’ve included SVN and GIT, and I’m sure you could trivially add CVS if need be. Other VC tools may not be such a good fit — in many cases, they encode project info as part of the path, so the standard ’show the working directory’ prompt is enough.

(On the other hand, if you’ve got one that needs special treatment, drop me a line and I’ll add it here.)

if which git > /dev/null
then
	parse_git_path() {
		if [[ -d .git ]]
		then
			git branch --no-color \
			| sed -rne '/^\*/s/^\* (.*)$/(git:\1) /p'
			return 0
		else
			return 1
		fi
	}
else
	parse_git_path() {
		return 1
	}
fi

if which svn > /dev/null
then
	parse_svn_path() {
		if [[ -d .svn ]]
		then
			local rroot=$(svn info | sed -ne 's/Repository Root: //p')
			svn info 		\
			| sed -rne "s#^URL: $rroot/(trunk|branches/[^/]*).*#(svn:^/\1) #p"
			return 0
		else
			return 1
		fi
	}
else
	parse_svn_path() {
		return 1
	}
fi

parse_vc_path() {
	parse_git_path \
	|| parse_svn_path
}

export PS1="\[\e]0;\$(parse_vc_path)\w\a\]${debian_chroot:+($debian_chroot)}\$(parse_vc_path)\w\$ "


The key is that bash performs command substitution on PS1 each time it prints it, so you can have whatever command sequence you want get run. In this case, it’s a script that does whatever processing is needed in order to determine the “branch”, if any, that you’re on.

Leave a Reply