Undo a Git commit (the safe way)
Which undo you need depends on whether you’ve pushed. Here’s how to pick the right one without losing work.
Look at recent history
Find the commit you want to undo.
git log --oneline -53f2a9c1 (HEAD -> main) Oops, wrong files 7c1d2e4 Update 2e8d6a1 Initial commit
Not pushed yet? Uncommit and keep the changes
The commit disappears but every change stays staged so you can fix it and commit again.
git reset --soft HEAD~1If the commit was already pushed, use git revert instead so you don’t rewrite shared history.
$ git log --oneline -1 3f2a9c1 (HEAD -> main) Oops, wrong files
Already pushed? Revert instead
Revert adds a new commit that cancels the old one, so teammates’ history isn’t rewritten.
git revertWent too far? Get it back
The reflog remembers every commit HEAD has pointed to, even after a reset.
git reflog3f2a9c1 HEAD@{0}: reset: moving to HEAD~1 8d4e7b2 HEAD@{1}: commit: The commit you thought was gone