Undoing and recovery
Revert a shared commit
Undo a published change by adding a new commit instead of rewriting shared history.
When a bad commit is already on the remote, do not rewrite history. Add a new commit that reverses its changes. That is what git revert is for.
Revert is different from reset. Reset moves your branch pointer. Revert leaves history intact and appends a correction on top. On a shared branch, that is usually what you want.
Suppose notes-project on main has a pushed commit that removed a line from README.md by mistake. You already pushed it. A teammate may have pulled it. Start with a clean working tree:
git status
git log --oneline -3
git show --stat HEAD~1
Pick the bad commit’s hash from git log. Then revert it:
git revert abc1234
Git applies the inverse patch and opens a commit message. Save and close the editor. Verify:
git log -3 --oneline
git show --stat HEAD
You should see the original bad commit still in history, plus a new revert commit on top. The README line comes back.
A revert can conflict when later work changed the same lines. Git stops and marks the file unmerged. Resolve it like a merge conflict, stage the result, then run git revert --continue. Use git revert --abort to return to the pre-revert state.
If you revert the wrong commit, run git revert HEAD on the revert commit to undo the undo. That adds another forward commit instead of erasing history.
After a successful revert, git log --oneline -3 shows the bad commit, your other work, and the revert on top. Shared teammates can pull normally.
Revert is safer for shared history because collaborators can fetch a normal new commit. Nobody has to replace an existing commit ID on their machine.
My rule: amend locally, revert on shared branches.
Try this in notes-project: commit a line to ideas.txt, commit another unrelated line, push both, then revert the first commit. Confirm the unrelated later change remains.
Lesson completed