Use separate .gitconfig files to easily jump between work and hobby projects

I'm programming as a job, but also work on several hobby projects. Increasingly, the code for my work projects and my hobby projects are set up in the same way and the code is stored in the same place.
Published:
This makes it easy to switch from one to the other, but it also creates the headache that I need some different configuration for each.
One example is that as a consultant, I want to commit code using my employer's e-mail address, but at home I want to use my personal one.
Let's see how we make the switch painless with different .gitconfig files.
Initial setup, file structure
I have my code in these directories:
C:\Work for work related projects
C:\Projects for hobby projects
I create two files in my home directory, ~
~/.gitconfig
~/.gitconfig-bjarte
.gitconfig will be the default configuration, the one I use for work. This is the config I write to when using commands like this:
git config --global user.name "Bjarte Aune Olsen"
.gitconfig-bjarte will be the alternate configuration.
In this post I'm only going to set up a single alternative, but you can have more than one, for example one for each client you are working for.
Content of .gitconfig
# Standard config for work
[user]
name = Bjarte Aune Olsen
email = bjarte.aune.olsen@myemployer.com
# Separate config for my private repos
[includeIf "gitdir:C:/Projects/"]
path = ~/.gitconfig-bjarte
Content of .gitconfig-bjarte
[user]
name = Bjarte Aune Olsen
email = bjarte@auneolsen.no
Check that both configs work
First check that git can read both configs.
Run git config with findstr on Windows (replace with grep on Linux) to see available email configurations:
git config --list --show-origin | findstr email
file:C:/Users/bjarte/.gitconfig user.email=bjarte.aune.olsen@myemployer.com
file:C:/Users/bjarte/.gitconfig-bjarte user.email=bjarte@auneolsen.no
Then check that the config changes in different directories.
First in a work project:
cd C:\Work\work-project\
git config user.email
bjarte.aune.olsen@myemployer.com
Then in a hobby project:
cd C:\Projects\hobby-project\
git config user.email
bjarte@auneolsen.no
Make sure your git client uses the global .gitconfig
This setup works nicely if you (like me) switch between the terminal and a separate git client, as long as the git client use the global .gitconfig and doesn't replace it with its own.
In GitKraken the default setting is to ignore the settings in .gitconfig and instead use its own. To switch this off, go to Preferences → Profiles and uncheck Keep my .gitconfig updated.