basnotes

 

Fix email address in Git commits

tip

As probably many of you, I have a personal and work email address. When working on my personal stuff, I want to use my personal email address for personal code commits and my work email address for work related commits.

Many a time I find I have used my work related email address for my personal work…

I hear you say, “you can set your email address in the local configuration of your personal repository!” And you are of course right:

git config user.name <user first and last name>
git config user.email <user email address>

But, every so often, I find after multiple commits after a new clone that I, again, forgot to specify this local configuration…

That is when I need means to rewrite the history of my repository and correct the email address. After looking around on the internet and more specifically on Stack Overflow. I found this answer with a reference to a GitHub help page handling this topic.

NOTE that changing the email address requires rewriting the Git history which will break local copies on other machines. Those will need to be cloned again to fix it.

So here, in short the solution GitHub provides:

git clone --bare https://github.com/user/repo.git
cd repo.git

Create and run this script:

#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Finally, after checking if your changes are correct, push the updated repository to the server:

git push --force --tags origin 'refs/heads/*'   

This has worked nicely for me and I was able to easily fix my email addresses.

Note that if you only have to fix a single commit, you can still use:

git commit --amend --author="first last<email>"

August 31, 2020