How to Undo a Commit in Git: The Complete Guide

At some point in your Git workflow, you may need to undo a commit—whether it’s to fix a mistake, rewrite history, or remove sensitive data. Git gives you powerful tools to undo commits safely and effectively, depending on your situation.

In this guide, we’ll walk through several ways to undo a Git commit, based on whether it has been pushed or not.


✅ Scenario 1: Undo the Most Recent Commit (Local Only)

If the commit has not been pushed to a remote, and you just want to undo the last commit:

🔹 Option A: Remove the commit and discard changes

git reset --hard HEAD~1
  • This completely removes the commit and all changes.
  • Use only if you’re sure you don’t need the changes.

🔹 Option B: Remove the commit but keep changes in working directory

git reset --soft HEAD~1
  • This undoes the commit but keeps your changes staged.
git reset --mixed HEAD~1
  • This undoes the commit and unstages the changes, but keeps them in your working directory.

✅ Scenario 2: Undo a Specific Older Commit

To remove or change an earlier commit (not just the most recent), use interactive rebase:

git rebase -i HEAD~N
  • Replace N with how many commits back you want to view.
  • In the editor that opens, replace pick with:
    • drop to delete a commit
    • edit to change the commit

⚠️ Only use this on local commits. Rewriting public history can cause conflicts for others.


✅ Scenario 3: Undo a Commit That Has Been Pushed

If the commit is already pushed to a remote repository, and you want to undo it:

🔹 Option A: Revert the Commit

git revert <commit_hash>
  • This creates a new commit that undoes the changes of the specified commit.
  • Ideal for safe undoing on shared branches.

Example:

git revert a1b2c3d

🔹 Option B: Reset and Force Push (Caution!)

If you’re sure no one else is working on the branch:

git reset --hard HEAD~1
git push origin main --force
  • This rewrites history and can be disruptive to others.

🧩 Summary of Commands

TaskCommand
Undo last commit, discard changesgit reset --hard HEAD~1
Undo last commit, keep changesgit reset --soft HEAD~1 or --mixed
Undo specific commit (interactive)git rebase -i HEAD~N
Revert a pushed commitgit revert <commit_hash>
Undo pushed commit (force push)git reset --hard HEAD~1 && git push --force

📌 Final Tips

  • Use git log to find the commit hash you want to undo.
  • Always back up or create a new branch before risky operations.
  • Avoid git reset --hard unless you’re sure—it discards changes permanently.
Sharing Is Caring:

Leave a Comment