Christian Giacomi

Git undo last commit

Posted — Apr 12, 2020

This will be a very short post, because it’s meant primarily as a way for me to remember a git command which I seldom use, but when I do, I never remember the exact syntax.

As they say:

If you want to remember somethinng, write it down

Undo a commit

In this case you will have to use the reset command and will have to specify the revision you want to rewind to.

Keeping your changes

To preserve the changes, use the --soft flag which will preserve your revisions. At this point you will be able to make any changes and re-commit them once you are done with your work.

$ git reset --soft HEAD~1

Dropping your changes

If instead you want to discard all the changes, you will have to use the --hard flag.

$ git reset --hard HEAD~1

The HEAD~1 syntax is a short form to specify how far back we want to rewind, ~1 specifies the last revision. Of course you can do HEAD~3 which would rewind the last 3 commits.

Or if you want to specify a specific revision you can simply to the following

$ git reset --hard 1cd9b7a3

Use with caution since you will lose the commits you have discarded.

Push the changes

To push the changes to your remote repo, you will have to use the -f option to force push, this will in effect strip the remote commits, so please make sure you exercise caution when doing so.

$ git push -f
If this post was helpful tweet it or share it.