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.
-
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/homeand~/repos/work. Put all your home repos in~/repos/homeand 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.) -
Next, edit
~/.gitconfigto include your primary email address. This can be either your work or home address, whichever you consider your main address for commits.If you prefer, you can also add the configuration from the command-line.
-
Now you need to create a
.gitconfigfile 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/.gitconfigand add a section that contains your work email address: -
The final step is to reference your new
~/repos/work/.gitconfigfile in your global~/.gitconfigfile. We can tell Git that we want to use the work config for all repos within the~/repos/worksub-directory: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>.