How to Undo the Most Recent Local Commits in Git: Step-by-Step Guide [2025]

Ever made a commit and immediately regretted it? Don’t worry – it happens to every developer! In this guide, you’ll learn exactly how to undo recent local commits in Git, with real-world examples and practical scenarios.

🔍 Quick Solution

For those in a hurry, here’s the most common solution:

# To undo the last commit but keep your changes
git reset --soft HEAD~1

# To completely undo the last commit and all changes
git reset --hard HEAD~1

💡 Understanding Git Reset Options

Let’s explore each reset option with a practical example. Imagine you have this simple project:

📁 my-project/
  ├── index.html
  ├── styles.css
  └── script.js

1. Soft Reset: Keep Your Changes

When you want to undo a commit but keep all your changes staged:

# Original state
$ git add index.html
$ git commit -m "Update header design"

# Oops, want to undo that commit!
$ git reset --soft HEAD~1

# Your changes are still there, just uncommitted
$ git status
On branch main
Changes to be committed:
  modified: index.html

2. Mixed Reset: Unstage Changes

To undo the commit and unstage changes (but keep them in your working directory):

$ git reset HEAD~1

# Changes are now unstaged
$ git status
On branch main
Changes not staged for commit:
  modified: index.html

3. Hard Reset: Complete Undo

⚠️ Warning: This option permanently discards changes. Use with caution!

$ git reset --hard HEAD~1

# Everything is gone, back to previous commit
$ git status
On branch main
nothing to commit, working tree clean

🔄 Alternative: Using Git Revert

Sometimes you want to undo changes while keeping the commit history (especially for shared branches):

# Create a new commit that undoes previous changes
$ git revert HEAD

# For multiple commits
$ git revert HEAD~3..HEAD

🚀 Pro Tips

  • 💾 Before any major undo operation, create a backup branch:
    git branch backup-branch
  • 🔍 Use git log --oneline to quickly identify commits to undo
  • ⚡ For multiple commits, use HEAD~n where n is the number of commits to undo

❌ Common Mistakes to Avoid

MistakeSolution
Using –hard without checking changesAlways use git status first
Undoing pushed commitsUse git revert instead of reset
Forgetting to create a backupCreate a backup branch before major changes

Can I recover after a hard reset?

Yes, using git reflog and git reset --hard HEAD@{n} where n is the reflog entry number.

What if I’ve already pushed the commit?

Use git revert instead of git reset to avoid history rewriting.

Leave a Reply