Here’s a quick walkthrough of my own process. I’ve often amended a commit like this:
shell> echo "bar" >> a
shell> git commit -a -m "made a bar"
shell echo "baz" >> a
shell> git commit --amend -C HEAD -a
Only to notice it was a whoops! I may have noticed it right away or noticed it after pushing, or noticed it the next day. So, I’ll run git reflog
:
shell> git reflog
f6ee9c3 (HEAD -> master) HEAD@{0}: commit (amend): made a bar
f899e59 HEAD@{1}: commit: made a bar
...
The reflog
may be really long, but in the above snippet it highlights two things. The first is that where an amend happened and the second is the SHA on thne next line which represents the point in time before the amend happened.
In the above, f6ee9c3
is the SHA to the new amended commit, the bad one we no longer wan.t
The commit below that, f899e59
, is what is what previously, the one we want to restore.
Then I reset hard to that SHA:
git reset --hard f899e59
If I had pushed I will now force push and then let anyone know who may have checked out that branch locally that I did so and that the new top of that branch should be f899e59
.
Now, depending on what you did before you amended the commit the previous line in the git reflog
output may show other than a “commit:”. For example, if the previous action you did was checkout the branch you’re on the reflog output may look like this:
shell> git reflog
6f8c68f (HEAD -> master) HEAD@{0}: commit (amend): made a bar
f899e59 HEAD@{1}: checkout: moving from some-branch to master
Here the previous line says “checkout:” instead of commit, but the SHA still points to the one we want to restore to.
There may be other ways to do this, but this is one way that I’ve found help.