How to revert a commit in Git
Undo a commit in Git using revert, reset, or amend depending on whether it has been pushed.
How to revert a commit in Git
Undo a commit in Git using revert, reset, or amend depending on whether it has been pushed.
Prerequisites
- Git installed.
Step-by-Step: Revert a Commit in Git
Revert a pushed commit— create a new commit that undoes the changes.
git revertis safe for shared branches because it does not rewrite history:git revert abc1234Undo the last unpushed commit— remove the commit but keep the changes staged:
git reset --soft HEAD~1Discard the last unpushed commit entirely— remove the commit and discard all changes:
git reset --hard HEAD~1Amend the last commit— modify the message or add forgotten files without creating a new commit:
git add forgotten-file.txt git commit --amend -m "Updated commit message"
Common Issues When Reverting in Git
git reset --hard permanently discards uncommitted changes. Use
git stash to save work in progress before resetting. Never use
git reset on commits that have been pushed to a shared branch — use
git revert instead.