Undoing commits | The Git Reset Command

It might happen that you create a commit containing files you did not want to commit, i.e. you added files to the commit accidentally, or that you want to undo your commits to put them into one commit later on. When it comes to undoing commits, the Git reset command comes in pretty handy.
When undoing commits, you can decide whether to keep your local changes (soft resetting) or whether you want to revert your local changes (hard resetting). We will cover these two cases in the following sections.
Usage of the Git reset command
You can use the Git reset command by specifying which n-th commit you want to reset to. Let’s say you have the following commit history:
In case that you wanted to reset to the commit “Did this and that 1” (i.e. resetting the commits “Did this and that 3” and “Did this and that 2”), you would specify HEAD~2:
Alternatively, you can use the commit hash to reset to a specific commit. To do the same as with HEAD~2, you would use the Git reset command by specifying the commit fa55a439cc213daf00d55468d04d6a8d96fa6e0c
:
The commits “Dis this and that 3” and “Did this and that 2” will then be reset (i.e. they won’t present anymore) and all the files of this commit are removed from the staging area. The resulting Git log will look as follows:
Soft resetting: Undoing commits while keeping your changes
In case that you wanted to reset to the commit “Did this and that 1” (i.e. resetting the commits “Did this and that 3” and “Did this and that 2”) while keeping your changes, you would need to use the Git reset command with the --soft
option as follows:
The soft reset leads to keeping your changes. Therefore, you can now add the files to be committed again, create the commit(s) and then push your commit(s).
Hard resetting: Undoing commits and reverting your changes
In case that you wanted to reset to the commit “Did this and that 1” (i.e. resetting the commits “Did this and that 3” and “Did this and that 2”) while not keeping your changes (i.e. reverting them), you would need to use the Git reset command with the --hard
option as follows:
The commits “Did this and that 3” and “Did this and that 2” will then be deleted and your changes will be reverted. As a result, your code will have the state of the commit fa55a439cc213daf00d55468d04d6a8d96fa6e0c
.
Leaving out the --hard
option will lead to a hard reset, too.
Reference
For full reference see Git reset documentation.