Git & GitHub ยท Chapter 21 of 42

git revert

`git revert` creates a new commit that undoes the changes from a previous commit, without rewriting history. This makes it safe to use on shared branches, unlike `git reset --hard`.

Because revert adds a new commit instead of deleting old ones, the full history โ€” including the mistake and its fix โ€” stays visible and traceable.

Syntax
git revert <commit-hash>

Reverting a commit

Run `git revert commit-hash` to create a new commit that undoes the changes introduced by that specific commit.

Revert vs reset

Revert is safe for shared history because it adds a new commit. Reset rewrites history by moving the branch pointer, which can be dangerous if others have already pulled those commits.

Example 1 (bash)
git revert 9c2e1aa
Output
[main 1f4b8cd] Revert "Fix crash when cart is empty"
 1 file changed, 5 deletions(-)

Creates a new commit that undoes the changes from commit 9c2e1aa.

Example 2 (bash)
git revert --no-commit 9c2e1aa
git commit -m "Revert bad fix, will redo properly"

Stages the revert without committing immediately, letting you customize the commit message.

Key points

  • git revert undoes a commit by creating a new, opposite commit.
  • It does not rewrite history, so it's safe for shared branches.
  • The original commit remains visible in history.
  • Reset rewrites history; revert adds to it safely.
๐Ÿ’ก Note: Prefer git revert over git reset --hard whenever undoing changes on a branch that others are also using.

๐Ÿ“ Quick Quiz

1. What does git revert do?

2. Why is revert safer than reset --hard for shared branches?

3. After reverting, is the original bad commit still visible in history?