In this tutorial, we are going to see how to undo git commit to fix mistakes. We will try to cover different scenarios like not pushed commits, pushed commits.
Delete unpublished (not pushed) commits
If you want to undo last commit and don't loose the changes use --soft:
git reset --soft HEAD~1
If you don't care about the changed you can use the --hard parameter, this could be useful for merge commits made by mistake:
git reset --hard HEAD~1
You can also use a commit hashes, for example suppose you have the following hashes:
3258054 3ad1b94 86ca9c7 5755e55
If you execute:
git reset --hard 5755e55
You will delete forever the changes of the commits: 86ca9c7,3ad1b94 and 3258054. After the execution of your comment, your HEAD will be 5755e55.
Fixing commits pushed without changing the history
When you have commits already pushed to remote repository and you don’t want to modify the history you can use the revert operation:
git revert 3258054 3ad1b94
You can also use git revert HEAD~1 to revert last commit.
The git revert will create new commits that will undo the previous hashes that you specified.
You can also use --no-commit:
git revert --no-commit 86ca9c7...HEAD
This will create revert changes of the commits 86ca9c7,3ad1b94 and 3258054.