How to replace email for GitHub history

Probably you also forgot to replace your old mail with the new one. Or commited and pushed the code from your working laptop. It’s totally fine, you’re not alone.

Here are the steps to fix your problem.

  1. Get the repo:
git clone --bare https://github.com/repo.git

2. Create a script file:

touch .sh

3. Fill the file with the content:

#!/bin/shgit filter-branch --env-filter '
OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Github username, i.e. BerAlIv"
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

You can also change conditions to:

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ] || [ "$GIT_COMMITTER_NAME" = "$OLD_NAME" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ] || [ "$GIT_AUTHOR_NAME" = "$OLD_NAME" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi

Do not forget to add OLD_NAME="your old name, i.e. BerAlIv" before the conditions

4. Run the script with:

sudo sh .sh

5. After executing the script you may remove the backup branch by executing:

sudo git update-ref -d refs/original/refs/heads/master

6. Then, upload all changes and tags using:

git push --force --tags origin master

7. Pull all changes with histories which were updated on previous steps:

git pull origin master --allow-unrelated-histories

Thank you for you time!

Alexey Berezin,
Graduate student from St Petersburg State University, Master’s
Front-end Developer from Yandex

LinkedIn
GitHub