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.

bash
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.

bash
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.

bash
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

SituationUseWhy
Commit is pushed and others may have itgit revertNo history rewrite; safe to pull
Commit is local and unpushedgit resetCleaner history; nobody else is affected
Several commits need undoinggit revert A..B or resetRevert preserves the audit trail
A merge introduced the problemgit revert -m 1Explicitly 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.