How to Revert an Amended Commit in Git
This article outlines reverting the git commit --amend
command. We use this command to add files to a previous commit to keep our repository clean.
In a scenario where we used the command by mistake, how would we revert the effects?
Revert an Amended Commit in Git
Let’s have a look at the example below.
In the example below, we have used the git commit --amend
command to add file changes to the latest commit in our master
branch.
We want to undo the amend and commit the file separately. How do we go about this?
We will need to move our current HEAD
to point at the old commit before HEAD
was moved. We can do this by running the command below.
$ git reset --soft HEAD@{1}
Note that we used HEAD@{1}
instead of HEAD~1
. The latter will take us to the parent node of the current HEAD
, which is not what we desire.
This should restore the old commit as it was before the amend. We should now have our modified file on the index.
Let’s confirm our case with the git status
command.
Alternatively, you can run the git reflog
command to get the old commit hash before we amend it. Either way, both HEAD@{1}
and the old commit hash combined with the git reset --soft
command will arrive at the same destination.
We can now commit the file the conventional way.
$ git commit -m "Modify run.py"
We now have a separate commit for our modified file.
In a nutshell, we can revert the effects of the git commit --amend
command using the git reset --soft
command. Keep in mind the HEAD@{1}
is different from HEAD~1
.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn