Multiple Email Addresses with a Default in Git

Someone pointed out to me that my commits to github were showing up using my work email address (and therefore my commits weren’t connected to the proper account). I do personal and professional work on the same laptop and I find myself wanting to commit one git repo via one email address and one repo to another.

The first idea I had was to set the global email address to the default and then set individual email addresses on a per-project basis. Git always uses the global email address if one’s set. Thanks, git. Anyway, I have a super-hacky workaround for this based partially on my PS1 code for my bash profile. The first thing you have to do is open your ~/.gitconfig file and remove the user.email line. This was originally set using git config --global user.email your@email.com, but we’ll be handling this more manually:

parse_git(){
	gb=$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1/")
	if [[ -z $gb ]]
	then echo -e ""
	else
		ge=$(git config user.email)
		if [[ -z $ge ]]
		then 
			git config user.email "morgan@gallerus.com"
			echo -e "morgan@gallerus.com:"$gb'\n\r'
		else echo -e $ge":"$gb'\n\r'
		fi
	fi
}
PS1="\[\033[1;33m\]\$(parse_git)\[\033[0;0m\]\[\033[1;32m\]\w\[\033[0;0m\]\n>"

This first line takes the output from git branch and finds a line with a * in it indicating that branch is selected. If it finds one, it re-searches for the name specifically. If either of these is not found, an empty string is returned.

in bash, [[ -z ]] indicates empty. If we find that the output of the branch script is empty, we stop checking. Otherwise, we set the local email address to the default.

Finally, we output the various bits for use in our PS1 shell prompt, but you don’t have to do that if you don’t want to.

The final output looks something like this (only more colorful)

morgan@gallerus.com:feedback
~/Documents/Workspace/gallerus
>

which is now how I like to set up my bash environment.

Leave a Reply

Your email address will not be published. Required fields are marked *