Searching "how to undo a git commit" returns 10 Stack Overflow answers with different commands and no explanation of which to use when. Here is the decision tree.
Step 1: Did you push the commit?
No, it is only local. You have the most options. Use git reset:
# Keep your changes staged (safest β nothing is lost) git reset HEAD~1 --soft
# Keep your changes unstaged but on disk git reset HEAD~1 --mixed
# Discard your changes completely (no recovery without reflog) git reset HEAD~1 --hard
Enter fullscreen mode
Exit fullscreen mode
Yes, it is already pushed. Do not rewrite history on a shared branch. Use git revert instead:
git revert HEAD # undo the most recent commit git push # push the undo commit
Enter fullscreen mode
Exit fullscreen mode
Revert creates a new commit that inverts the changes.β¦