Tour of Git
History & Undoing Changes / Lesson 3.6

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 revertgit reset
HistoryPreserved (new commit added)Rewritten (commits removed)
Shared branchesSafeDangerous
Undo methodCreates inverse commitMoves 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:

  1. Create a file and commit it:
    • echo "hello" > greeting.txt && git add greeting.txt && git commit -m "Add greeting"
  2. Make a second commit:
    • echo "goodbye" >> greeting.txt && git add greeting.txt && git commit -m "Add farewell"
  3. Check the file: cat greeting.txt — shows both lines
  4. Revert the second commit: git revert HEAD --no-edit
  5. Check the file again: cat greeting.txt — shows only "hello"
  6. 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 revert is 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
🎯

Goal

Create commits, then safely undo one using git revert

Terminal
$

No commits yet. Run `git init` and create your first commit.