‹ jan0sch.de

Change commit author in git history

2016-06-03

If you ever need to change the author of a commit (or several) within a git repository, you can use the following script:

#!/usr/bin/env bash

usage() {
  echo "Please set the following enviroment variables:"
  echo "  OLD_EMAIL : your-old-email@example.com"
  echo "  NEW_EMAIL : your-correct-email@example.com"
  echo "  NEW_NAME  : Your Correct Name"
  echo "Then run the script again from a git repository directory."
  echo "Example: OLD_EMAIL=alice@example.com NEW_EMAIL=bob@example.com NEW_NAME=\"Bob Doe\" $0"
}

if [ ! -d .git ]; then
  echo "Current directory is not a git repository!"
  exit 1
fi

if [ -z "${OLD_EMAIL}" ] || [ -z "${NEW_EMAIL}" ] || [ -z "${NEW_NAME}" ]; then
  usage
  exit 1
fi

echo "Going to rewrite git history and changing commit authorship."

git filter-branch --env-filter '
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$NEW_NAME"
    export GIT_COMMITTER_EMAIL="$NEW_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$NEW_NAME"
    export GIT_AUTHOR_EMAIL="$NEW_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

echo "Finished."

Attention!

Beware that the whole history of the repository will be rewritten! This means that other users will have to rebase their changes.