[git] Reverting an accidental commit/amend using reset

Alright. So this one might sound a special case, but there are chances that something like this scenario might turn up too, while playing with git.

Scenario:

You are working on top of a commit de7504f : My original commit, made some changes, and you really wanted to make it into a new commit, but accidently you gave git commit --amend and you are now in the edit commit message of de7504f.

Once saved, you can see in git log that you are in a new commit-id: 7645040: My original commit and amended change.

This can be equivalent to typing git commit, typing in the commit message, saving it – and later thinking – “God, I shouldn’t’ve committed it”.

Solution:

The idea is to run git reset and it would just take you back to a point where you have the changes staged, but not committed yet. To be more human, this is the place after you have made your changes, and typed in git add too.

You can get the commit-id straight from git log, but for my above scenario, since it was an amend, it might not just work. For that, we got git reflog

git reflog

it would list out commit id of every single change you did including amend, rebase, chgeckout, reset etc.

7645040 HEAD@{0}: commit (amend): My original commit and amended change
de7504f HEAD@{1}: commit: My original commit

Yay! Now you need to just run

git reset 7645040 
git status

and you are back in history where you have git add -ed the files, but not done git commit --amend yet. You can add those to a separate commit, or stash it or do whatever.

If you pass git reset 7645040 --hard, all changes which you did after 7645040 would be just thrown off, so use it with caution.

References: https://git-scm.com/docs/git-reset

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s