Here you will learn how to undo a commit (no matter it has been pushed or not have been pushed yet) in a safe and simple way. Changing the last commit gives more choices if you want to change the remote commit history and what you should do in various situations.
Undo a commit that hasn’t been pushed yet
If you made some mistakes in a commit, you can redo it in a new commit using
--amend option. Just fix your mistakes, stage (add) them and make a new commit as below:
# Redo the last commit. # --amend, replace the last commit with a new one. $ git commit --amend
If above solution does not suit you,
reset can be used to just undo the commit (be careful to use reset):
# Discard the last commit. The commit's modifications in working tree are kept. $ git reset HEAD~ # Discard the last commit. The commit's modifications in staging area are kept. $ git reset --soft HEAD~ # Discard the last commit. The commit's modifications in working tree are not kept. $ git reset --hard HEAD~
Undo a commit that has been pushed
If a commit has been pushed to the remote repository, changing the history in the remote repository is not a good idea. You can let Git to make a new commit which reverses the modifications in the last commit.
git revert command works for you :
# Reverse a commit. $ git revert -m 1 HEAD
Afterwards, push it to the remote repository again.