Undoing Changes: git revert
git revert, safe undo, revert commit, revert merge commit, revert vs reset
Undoing Changes: git revert
Git revert creates a new commit that undoes the changes introduced by a specified commit. Unlike reset, revert is safe for shared repositories because it adds to history rather than rewriting it.
Reverting a Commit
git revert abc1234Replace abc1234 with the commit hash you want to undo. Git will create a new commit with the opposite changes, effectively cancelling out the original commit's effect. Your history shows both the original commit and the revert commit.
Reverting Without Opening an Editor
git revert abc1234 --no-editThis automatically uses the default revert message without opening your text editor.
Reverting a Range of Commits
git revert HEAD~3..HEADThis reverts the last three commits. Each gets its own revert commit unless you use --no-commit to stage them all and commit once.
Reverting a Merge Commit
Merge commits have two parents, so you must specify which parent represents the mainline:
git revert -m 1 merge-commit-hashThe -m 1 flag tells Git that parent 1 (the branch you merged into) is the mainline.
When to Use Revert
Use revert on any commit that has been pushed to a shared repository. It is the safest way to undo mistakes in public history because it never overwrites existing commits.
