Git Tips #6 - Using Git with Multiple Email Addresses

If like me you're using Git for multiple client projects and open source work on GitHub on the same machine, you'll hit a problem early on where the email address you use for GitHub is different to the email address you need to use for client projects.

Why is this a problem?

Usually you'll set your email address globally for Git:

git config --global user.email user@email.com

If you push a commit with an author email address which isn't yours, the commits won't be linked to you.

I'm mainly using GitHub for open source and GitLab for client work at the moment, so I'll show examples from those systems. They both use the commit author's email address to link commits to a user.

In GitHub If you use an email address that isn't linked to your account, your commits will look like this:

Unknown user in GitHub

And in GitLab:

Unknown user in GitLab

The solution

The solution is to make use of Git config conditional includes.

We will create a .gitconfig file with settings for work repositories, another for GitHub, and then reference them from the global Git config file.

We need to make two folders, one called github and another called work. The config will tell Git to use your GitHub email for repros in the github folder and your work email for repros in the workfolder.

First, add the following to your global Git config file at ~/.gitconfig:

[includeIf "gitdir:github/"]
  path = .gitconfig-github
[includeIf "gitdir:work/"]
  path = .gitconfig-work

Also, remove the email key in the [user] section if you have it.

Next create a file at ~/.gitconfig-github with the following content. You'll need to use your email address here:

[user]
  email = kevin@kevinkuszyk.com

And create a file at ~/.gitconfig-work with the following content. Use your work email address here:

[user]
  email = kevin.kuszyk@work.com

Now, any Git repros under a folder called github anywhere on your file system will use the GitHub email address, and any repros under a folder called work will use your work email address.

References