Undoing commits

Suppose we have a repository that looks like the one on the image and we want to undo the last commit (088455d). Since this commit is only in our local repository, we use the reset command.

Undoing commits 1

This command has three options that you should know about:

  • --soft removes from the repository only. This means that it undoes the git commit action, but our changes are still in the staging area.
  • --mixed removes from the repository and the staging area. This means that it undoes both git commit and git add action. Our changes will still be in our working directory.
  • --hard removes from the repository, the staging area, and the working directory. This means that we are getting rid of our work for good.
Undoing commits 2

When we reset commits we need to supply the target position for the HEAD pointer. In this case, since we are going to be working with the last commit, we should tell Git that the target commit for the HEAD pointer is the commit before last. So we run

git reset --soft HEAD~1

The last commit is now gone from our repository and we have changes that have already been staged and are ready to be committed. So it's as if we had never run git commit that last time.

If we instead want to remove changes from the repository and the staging area, then we run

git reset --mixed HEAD~1

The --mixed option is the default, so we can omit it. Just as before, the commit is now gone from the repository. But this time notice that the changes are in the working directory only. They have not been staged.

Undoing commits 3
Undoing commits 4

Lastly, if we want to remove changes from the repository, the staging area, and the working directory, then we run

git reset --hard HEAD~1

Notice that now, when we run git status -s Git is staying that there's nothing there. This is because we just deleted our changes from everywhere. It's as if we had never written that code to begin with.