When to Use git reset vs git revert: A Practical Guide for Safe Code Rollbacks
This article explains the differences between git reset and git revert, shows how each command moves the HEAD pointer, demonstrates step‑by‑step examples for undoing erroneous commits, and advises when to prefer revert to preserve history and avoid forced pushes.
During iterative development, developers often need to undo mistaken commits; beginners may panic while experienced engineers calmly revert changes using Git.
The two primary commands for rolling back are git reset and git revert, each with distinct behavior.
git reset
Consider a repository with four commits: A and B are correct, C and D are erroneous, and HEAD points to D.
Moving HEAD back to commit B (a0fvf8) discards C and D locally: git reset --hard a0fvf8 After the reset, HEAD points to B, but the remote repository still points to D. Pushing without force fails, so a forced push is required: git push -f This approach loses the history of C and D, which may be undesirable, and many companies forbid using git reset for rollbacks.
git revert
git revertcreates new commits that undo the changes of specified commits while preserving the original history.
To revert the example, first revert D then C (newer to older):
git revert 5l4ker
git revert 76sdebThis produces new commits D' and C', keeping the original erroneous commits visible.
For many erroneous commits, reverting each individually is inefficient. A batch revert can be performed with: git revert OLDER_COMMIT^.NEWER_COMMIT This keeps the bad commits in history and moves HEAD forward, allowing a normal git push without force—an approach encouraged in enterprises.
Complex scenario with an intermediate bad commit
If an erroneous commit sits in the middle of a series (e.g., A‑B‑C‑D where C is bad), resetting to A would also discard the good commit C. Instead, reset to the commit before the bad range, then cherry‑pick the good commit back:
git reset --hard A
git cherry-pick CIn summary, git reset rewrites history and can cause loss of later commits, while git revert safely creates new commits that undo changes, preserving the original history and avoiding forced pushes.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
