How to undo the last Git commit
· Category: Git
Short answer
Use git reset for local unpushed commits and git revert for public commits you need to undo safely.
Steps
- Undo last commit but keep changes:
git reset --soft HEAD~1
- Undo last commit and discard changes:
git reset --hard HEAD~1
- Create a reversal commit:
git revert HEAD
- Amend the last commit:
git commit --amend
Tips
--softis safest for undoing while preserving your work.--hardis destructive; ensure you do not need the changes.revertis the correct choice for shared history.
Common issues
- Resetting pushed commits breaks history for collaborators.
- Accidental
--hardcan be recovered withgit reflogin most cases.