git revert — Safely Undoing Commits
The git revert command creates a new commit that undoes the changes from a previous commit. Unlike git reset, it doesn't rewrite history — it adds to it.
Revert vs Reset
git revert | git reset | |
|---|---|---|
| History | Preserved (new commit added) | Rewritten (commits removed) |
| Shared branches | Safe | Dangerous |
| Undo method | Creates inverse commit | Moves HEAD backward |
Use git revert when the commit you want to undo has already been pushed to a shared branch. Use git reset only for local, unpushed work.
How It Works
A — B — C — D (before revert)
↓
A — B — C — D — D' (after git revert D)
Commit D' contains the exact opposite of the changes in D. The original commit D stays in history.
Basic Usage
git revert HEAD # Revert the most recent commit
git revert abc1234 # Revert a specific commit by SHA
git revert HEAD~2 # Revert the commit two before HEAD
Git will open your editor to write a commit message. The default message describes which commit was reverted.
Try it!
Practice reverting a commit:
- Create a file and commit it:
echo "hello" > greeting.txt && git add greeting.txt && git commit -m "Add greeting"
- Make a second commit:
echo "goodbye" >> greeting.txt && git add greeting.txt && git commit -m "Add farewell"
- Check the file:
cat greeting.txt— shows both lines - Revert the second commit:
git revert HEAD --no-edit - Check the file again:
cat greeting.txt— shows only "hello" - Check the log:
git log --oneline— all three commits are visible, including the revert
Reverting Older Commits
You can revert any commit, not just the most recent one. Git will figure out what changes to undo:
git log --oneline # Find the commit SHA
git revert abc1234 # Revert that specific commit
If the revert causes a conflict (because later commits depend on the reverted changes), Git will ask you to resolve it manually.
Key Points
git revertis safe for shared/public branches — it never rewrites history- It creates a new commit that undoes the changes from the target commit
- The original commit remains in the log for traceability
- If conflicts arise, resolve them and run
git revert --continue