kelan.io

Delete last commit in Git

First, set up this alias:

$ git config --global alias.delete-last-commit "reset --hard HEAD^"

Then you can just do:

$ git delete-last-commit

Or even just git del<tab>, if you have auto-complete set up in your shell.

Since this is messing with the history of the branch, the standard cautions apply about doing this with shared branches. But, for local-only branches, this can be quite handy.

I often use this when I realize I’ve been doing work on the wrong branch. For example, if I just made a commit on master that should have been the start of a new topic branch, I do just this:

$ git branch new-topic  # creates the new topic branch here, but don't switch to it
$ git delete-last-commit  # move master back to where it belongs
# optionally, create a new branch to work on
$ git checkout new-topic
# continue work on new-topic

And, a nice thing to keep in mind about git is that if you can actually still get the commit back if you realize you actually do need it, by using the reflog.