Git Pills: avoid committing with an unwanted user name and email

Do you use different users for different repos?
Have you ever committed your code to a repository using a wrong user name and email?

I did it many times. Here a way to stop it :)

I used to set up my default user.name and user.email in Git global configuration, like this:

Setting up user info globally

Shell

1

2

$git config--global user.email"you@example.com"

$git config--global user.name"Your Name"

For using different user info in different repos, as you may know, you can set up them locally by repository in this way, overriding global ones:

Setting up user info locally in current repository

Shell

1

2

$git config user.email"you@example.com"

$git config user.name"Your Name"

But I usually forget to do it, until I do a git log and I see my commit with wrong user and email… :|
Fortunately, there’s a way to avoid this.

First, delete global user config, this is pure evil.

Using Git in a shell, these are the commands for deleting user name and email:

Unset user. name and user.email

Shell

1

2

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

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

The more drastic way is to completely delete the user section:

Removing user section from global config file

Shell

1

git config--global--remove-section user

Alternatively, you can directly edit your user’s .gitconfig file (e.g C:\Users\<username>\.gitconfig file in Windows).
If you don’t know where configuration are stored, there’s a Git command to show them all:

Show all Git configurations and its origin

Shell

1

$git config--list--show-origin

You have to delete these two lines under the [user] section (you can delete even the [user] itself, as we have seen before):

1

2

3

[user]

name=Ferdinando Santacroce

email=nando@fakemail.com

Well, even doing this, while committing Git tries to auto-detect user and email from your system.

To avoid this, set this configuration variable:

Setting useConfigOnly to true

Shell

1

$git config--global user.useconfigonlytrue

Now, if you try to commit for the first time in a repo, Git will force you to set up a user name and email before: