iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

git revert

`git revert` produces a NEW commit that undoes the changes of a previous commit. Unlike `git reset`, history stays linear and the revert is itself a normal commit that pushes cleanly. It is the right tool for backing out a change that is already public — the undo is visible, attributable, and never rewrites someone elses history.

Revert single, range, merge, and dry-run

EXAMPLE
# 1) Revert a single bad commit by hash
git revert 9fceb02
# Opens an editor for the revert commit message; defaults to 'Revert <subject>'.

# 2) Revert without pausing for the editor (CI / script-friendly)
git revert --no-edit 9fceb02

# 3) Stage the inverse, but DO NOT commit yet — useful when you want to
#    combine the revert with other changes in a single commit
git revert --no-commit 9fceb02
git revert --no-commit a1b2c3d
# review, maybe edit some files, then:
git commit -m 'Roll back broken shipping logic + reword copy'

# 4) Revert a range of commits
git revert OLDEST^..NEWEST     # inclusive range, in reverse order
git revert --no-edit HEAD~3..HEAD

# 5) Revert a MERGE commit — say which side you want to KEEP via -m N
#    -m 1 keeps the parent on the side you merged INTO (mainline)
#    -m 2 keeps the parent that came IN
git revert -m 1 <merge-sha>

# 6) Abort a revert mid-way if you change your mind
git revert --abort           # if the editor is still open or there are conflicts
git revert --skip            # skip this commit in a range revert

# 7) Conflict during a revert — fix it like a merge conflict
git status
# <hack hack>
git add path/to/file
git revert --continue

# 8) Reverting a revert (yes, this is a thing)
git revert <revert-sha>      # restores the original change in a new commit

# 9) See what a revert WOULD do without committing or staging
git show --stat 9fceb02       # see the diff of the original commit
git diff HEAD HEAD~1          # confirm what reverting HEAD would change

# 10) The decision tree
# - Commit is unpublished?     -> 'git reset HEAD~1' is cleaner (no revert commit)
# - Commit is published?       -> 'git revert' (never rewrite shared history)
# - Need to bring back PART?   -> 'git checkout <good-sha> -- file' then commit
# - Need to back out a merge?  -> 'git revert -m 1 <merge-sha>'

Why it matters

For published commits, always prefer revert over reset --hard + force-push. Revert keeps every collaborators clone honest; force-push leaves teammates with orphaned branches and CI jobs running on commits that no longer exist on the remote, which is exactly the failure mode that destroys an afternoon for everyone else.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
git revert 4d5e6f7         # create a new commit that undoes 4d5e6f7
# Safer than reset for shared history.
Try it Yourself »

Discussion

Loading…