How to configure Git to commit using different emails for work and home repos

Today I learnt …

It’s a common problem: you commit code to a repo, push, and then realise you’ve used your personal email to commit to a work repo (or vice versa). The effects range from mildly annoying (your contributions to the repo are now split between two authors) to disastrous (your awful boss claims you’re committing to open-source projects on work time). Fortunately, it’s easy to configure Git to ensure that this can’t happen.

  1. First you need to split your home and work repos into two separate directories. Say you keep your repos in ~/repos; create two sub-directories, ~/repos/home and ~/repos/work. Put all your home repos in ~/repos/home and all your work repos in ~/repos/work. (The names and locations of the sub-directories don’t matter — they don’t even need to share the same parent directory.)

  2. Next, edit ~/.gitconfig to include your primary email address. This can be either your work or home address, whichever you consider your main address for commits.

    [user]
        email = your.primary.address@example.com
        name = Your Name
    

    If you prefer, you can also add the configuration from the command-line.

  3. Now you need to create a .gitconfig file in the sub-directory that contains the repos that match your secondary email address. Let’s say you’re using your personal email address as your primary email address. In this case create ~/repos/work/.gitconfig and add a section that contains your work email address:

    [user]
        email = your@work.address.example.com
    
  4. The final step is to reference your new ~/repos/work/.gitconfig file in your global ~/.gitconfig file. We can tell Git that we want to use the work config for all repos within the ~/repos/work sub-directory:

    [includeIf "gitdir:~/repos/work/"]
        path = ~/repos/work/.gitconfig
    

    The trailing slash on the end of "gitdir:~/repos/work/" is required.

With that done, when you run git commit from within ~/repos/work you’ll commit as Your Name <your@work.address.example.com>. When you commit from ~/repos/home — in fact any directory outside ~/repos/work — you’ll commit as Your Name <your.primary.address@example.com>.