If you use git for both personal and work projects, you’ve probably run into this: commits going out with the wrong email address because your global ~/.gitconfig is set to your personal account, or vice versa.

Starting with git 2.8.0, there’s a clean, officially supported solution.

The setup Link to heading

First, remove your name and email from the global config:

git config --global --unset-all user.name
git config --global --unset-all user.email

Then enable useConfigOnly:

git config --global user.useConfigOnly true

Now, any attempt to commit in a repository that doesn’t have identity details configured will fail with an error:

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: no name was given and auto-detection is disabled

This is intentional: the error forces you to set the correct identity per repository before you can commit.

Per-repository configuration Link to heading

In each repository, set the identity once:

# In a personal repo:
git config user.email "personal@example.com"
git config user.name "Michele Bologna"

# In a work repo:
git config user.email "m.bologna@company.com"
git config user.name "Michele Bologna"

This writes to the repository’s local .git/config, which takes precedence over the global config.

Automating it with conditional includes Link to heading

If you keep all work repos under a specific directory (e.g., ~/work/), git’s includeIf directive can apply a separate config file automatically, with no manual git config needed per repo:

# In ~/.gitconfig
[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work
# In ~/.gitconfig-work
[user]
    email = m.bologna@company.com
    name = Michele Bologna

This approach scales better if you have many repositories. The includeIf + useConfigOnly combination means you get automatic identity switching based on directory, with a safety net that prevents accidental commits under the wrong identity.