How to Delete the Previous Commit in Git

Made a mistake in your last commit? Pushed the wrong code or forgot to include a file? Don’t worry—Git offers several ways to delete or undo the most recent commit.

In this blog post, you’ll learn how to safely delete the previous commit, and which method is best depending on your situation.


⚠️ Before You Begin: Know the Risks

💡 If you’ve already pushed the commit to a shared repository, be careful—modifying history can affect collaborators. When working with others, prefer reverting instead of resetting.


🧹 Option 1: Delete Last Commit but Keep Changes (Soft Reset)

If you want to remove the last commit but keep your code (so you can fix it or recommit):

git reset --soft HEAD~1

This:

  • Removes the last commit
  • Moves changes back to the staging area
  • Allows you to amend or recommit easily

Safe for local changes, and ideal for small fixes.


🔥 Option 2: Delete Last Commit and Discard Changes (Hard Reset)

To completely delete the last commit and all changes that came with it:

git reset --hard HEAD~1

This:

  • Removes the last commit
  • Deletes any file changes introduced by that commit

⚠️ Warning: This is irreversible unless you’ve backed up or pushed your code elsewhere.


🔄 Option 3: Undo a Commit with git revert (Safe for Shared Repos)

If you already pushed the commit to GitHub or a shared repo, use:

git revert HEAD

This:

  • Creates a new commit that undoes the changes in the last commit
  • Keeps history intact
  • Is safe for shared branches

✅ Best practice for team collaboration and public repositories.


🧠 Summary Table

GoalCommandKeeps Code?Safe for Shared Repo?
Delete commit, keep changesgit reset --soft HEAD~1❌ (use before push)
Delete commit and changesgit reset --hard HEAD~1❌ (use with caution)
Undo commit with a new revert commitgit revert HEAD

🛡 Pro Tip: Backup Before Resetting

Always create a backup branch before using --hard reset:

git branch backup-before-reset

This gives you a restore point in case something goes wrong.


📌 Final Thoughts

Deleting or undoing a commit in Git is a powerful tool, but it comes with responsibility. Use reset when working locally, and revert when working with others. With the right approach, you can keep your commit history clean, your team happy, and your development workflow smooth.

Sharing Is Caring:

Leave a Comment