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?
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?
The safe way depends on one question: have you already pushed the commit?
Not pushed yet (only on your machine):
git commit --amend -m "Better message"git add file.txtthengit commit --amend --no-editgit reset --soft HEAD~1git reset HEAD~1git reset --hard HEAD~1(careful: this deletes work)Already pushed (others may have pulled it):
git revertcreates a new commit that undoes the old one. History stays intact, so nobody else's copy breaks. Avoidresetplusgit push --forceon shared branches likemain.Committed to
maininstead 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 branchLost something?
git refloglists everywhere your branch has pointed recently, even after a hard reset. Find the commit there and rungit reset --hard <sha>orgit branch rescue <sha>to get it back.What's the worst Git mistake you've had to recover from?