How to update the author of a Git commit

Updated: January 27, 2024 By: Guest Contributor Post a comment

Introduction

Git is a versatile version control system that tracks changes in source code during software development, but sometimes users might need to alter the commit history for various reasons, such as correcting an email address or author name. In this tutorial, we will discuss how to update the author information of a Git commit. We will start with the basic commands and gradually move to more advanced techniques.

Updating the Last Commit

If you’d like to change the author information of the most recent commit, you can easily do so by using the git commit --amend command:

git commit --amend --author="New Author Name <[email protected]>"

This will open up an editor allowing you to modify the commit message. Save and exit to apply the changes.

Output:

[master 1d3a5b6] Updated message (1 file changed, 1 insertion(+))

Correcting Author Information across Multiple Commits

Sometimes you need to change author information across several commits. This can be done using an interactive rebase:

git rebase -i HEAD~5

This command will allow us to interactively edit the last 5 commits. Replace ‘pick’ with ‘edit’ beside the commits you want to modify.

Now run this command for each commit:

git commit --amend --author="New Author Name <[email protected]>"

Then proceed with:

git rebase --continue

Repeat this process for each commit you selected to be edited.

Automated Script to Change Author Information

For changing the author information on a large number of commits, a script can be more effective.

Create a file named change-author.sh with the following content:

#!/bin/sh

OLD_EMAIL="[email protected]"
CORRECT_NAME="Correct Name"
CORRECT_EMAIL="[email protected]"

git filter-branch --env-filter '

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

This script uses git filter-branch to change the commit author globally. Execute it with:

sh change-author.sh

Warning: This will rewrite your commit history!

Conclusion

In this tutorial, we learned how to update the author of a Git commit using git commit --amend, interactive rebase, and an automated script with git filter-branch. These tools are powerful and can help maintain a clean and accurate commit history, but remember that altering commit history, especially published history, should be done with caution.