Revert the latest commit
The resulting commit reverses the patch: added lines are removed, removed lines are restored. The original commit stays in history, which is exactly what you want on a shared branch.
git revert HEAD
# opens an editor with a generated message, then commits the inverse change
git revert --no-edit HEAD # use the default message
Revert an older commit
Any commit can be reverted by its hash. If the changes since then touched the same lines, the revert produces conflicts that you resolve like a merge.
git revert 4f2c1ab
# conflicts?
git status # see conflicted files
# edit files, then:
git add resolved.txt
git revert --continue
# or abandon the revert
git revert --abort
Reverting a merge commit
A merge commit has two parents, so Git needs to know which side to keep. -m 1 keeps the mainline (the branch you merged into); -m 2 keeps the merged branch.
git revert -m 1 <merge-sha>
Reverting a merge does not let you re-merge that branch later without reverting the revert, because Git still considers the branch merged. Revert the revert when you want the changes back.
Revert vs reset
| Situation | Use | Why |
|---|---|---|
| Commit is pushed and others may have it | git revert | No history rewrite; safe to pull |
| Commit is local and unpushed | git reset | Cleaner history; nobody else is affected |
| Several commits need undoing | git revert A..B or reset | Revert preserves the audit trail |
| A merge introduced the problem | git revert -m 1 | Explicitly chooses the mainline |
After the revert
- Run the tests: the revert may conflict semantically with later changes.
- If the change will be reintroduced, revert the revert instead of reapplying the patch blindly.
- Document why in the revert message; future readers need the context.