devlk
c/learning u/devlk Team

How do I undo a commit in Git?

Team FAQ: this question comes up often, so we've answered it below. Add your own experience, or a different view, in the comments.

You committed something by mistake: the wrong files, a bad message, or on the wrong branch. How do you undo it safely?

1
1 comment
No account needed: you'll get a random guest name, kept on this device. Or sign up to choose yours.
Sort by: Best Top New Old
devlk Team·

The safe way depends on one question: have you already pushed the commit?

Not pushed yet (only on your machine):

What you want Command
Fix the last commit message git commit --amend -m "Better message"
Add a forgotten file to the last commit git add file.txt then git commit --amend --no-edit
Undo the last commit, keep the changes staged git reset --soft HEAD~1
Undo the last commit, keep the changes unstaged git reset HEAD~1
Undo the last commit and throw the changes away git reset --hard HEAD~1 (careful: this deletes work)

Already pushed (others may have pulled it):

git revert <commit-sha>
git push

git revert creates a new commit that undoes the old one. History stays intact, so nobody else's copy breaks. Avoid reset plus git push --force on shared branches like main.

Committed to main instead of a feature branch (not pushed):

git branch my-feature        # save your commit on a new branch
git reset --hard origin/main # move main back to match the remote
git switch my-feature        # continue working on the branch

Lost something? git reflog lists everywhere your branch has pointed recently, even after a hard reset. Find the commit there and run git reset --hard <sha> or git branch rescue <sha> to get it back.

What's the worst Git mistake you've had to recover from?

1