DEV Community

Mohamed Idris
Mohamed Idris

Posted on

How to Undo a Git Commit Without Losing History

We've all been there — you made a commit, pushed it, and then realized: that was a mistake.

The good news? Git has a safe way to undo it without rewriting history.

The Problem

You might think of using git reset to go back in time. But if you've already pushed the commit to a shared branch, resetting and force-pushing can cause problems for everyone else on the team.

The Better Way: git revert

git revert creates a new commit that undoes the changes from a previous commit. Your history stays intact — you just add an undo step on top.

How to Do It

Step 1: Find the commit you want to undo

git log --oneline
Enter fullscreen mode Exit fullscreen mode

You'll see something like:

a8636a4 Tailor portfolio for e-commerce role
d56677a Fix hover effect
5315182 Add new project
Enter fullscreen mode Exit fullscreen mode

Copy the hash of the commit you want to revert (e.g. a8636a4).

Step 2: Revert it

git revert a8636a4 --no-edit
Enter fullscreen mode Exit fullscreen mode
  • a8636a4 — the commit hash you want to undo
  • --no-edit — skips the editor and uses the default revert message

Git will create a new commit like:

bf880c5 Revert "Tailor portfolio for e-commerce role"
Enter fullscreen mode Exit fullscreen mode

That's it. Your mistake is undone and your history is clean.

When to Use git revert vs git reset

git revert git reset
Creates a new commit Yes No
Safe for shared branches Yes No
Rewrites history No Yes

Rule of thumb: If the commit is already pushed, use git revert. If it's only local, git reset is fine.

Summary

# See your commits
git log --oneline

# Revert the one you don't want
git revert <commit-hash> --no-edit
Enter fullscreen mode Exit fullscreen mode

Simple, safe, and no drama. That's the Git way.

Top comments (0)