How to Change the author of commits using a rebase (Git)

Oct 04, 2020

When starting to work on a new project, it is common to forget to set the author name and author email address for the specified project. Therefore, you will often have commits in your local branch that have been committed with the wrong username and/or email ID.

Step 1 : We need a branch, as always with Git. Name the branch resetAuthorRebase and make it track origin/master. Use the following command to achieve this:

git checkout -b resetAuthorRebase -t origin/master

Step 2 : Change the author of the HEAD commit as follows:

git commit --amend --reset-author

Step 3 : Verify that you have changed it using the Git log command:

git log --format='format:%h %an <%ae>' origin/stable-3.2..HEAD

Step 4 : What we really wanted was to change the author of all the commits. To do this, we will rebase onto the origin/stable-3.2 branch; then, for each commit, we will stop to amend and reset the author. Git can do most of that work with --exec option for the git rebase, as follows:

git rebase --interactive --exec "git commit --amend --reset-author" origin/stable-3.2

Step 5 : As you can see, Git has opened the rebase's to-do list for you, and between every commit, you have the exec keyword and the command we specified on the command line. You can have more exec lines between commits if you have a use case for them. Closing the editor will start the rebase.

Step 6 : As you will see, this process is not very good, as the commit message editor opens every time and you have to close the editor to allow Git to continue with the rebase. To stop the rebase, clear the commit message editor and Git will return to the command line; then, you can use git rebase --abort as follows:

git rebase --abort

Step 7 : To achieve what we really want, you can add the --reuse-message option for git commit; this will reuse the commit message for the commit you will specify. We want to use the message of HEAD, as we are going to amend it to the HEAD commit. So, try again, as shown in the following command:

git rebase --interactive --exec "git commit --amend --reset-author --reuse-message=HEAD" origin/stable-3.2

Step 8 : Git provides an output indicating that the action was a success; however, to verify this, you can execute the previous Git log command and you should see that the email address has changed on all the commits, as shown in the following command:

git log --format='format:%h %an <%ae>' origin/stable-3.2..HEAD