How to Delete the Last Commit in Git (Safely)

There are times during development when you realize the last commit you made contains a mistake — maybe a typo, unwanted files, or the wrong message. The good news? Git allows you to delete or undo that last commit with a few simple commands.

In this post, we’ll show you how to delete the last commit in Git, depending on your situation — whether it’s been pushed or not.


⚠️ Before You Begin

Understand whether the commit has been pushed to a remote repository or not:

  • If NOT pushed: You can safely delete or modify it locally.
  • If already pushed: Be careful — rewriting history affects others working on the same repository.

🔧 Option 1: Delete Last Commit (Local Only)

If the last commit hasn’t been pushed yet:

git reset --soft HEAD~1

This deletes the last commit but keeps the changes staged (in the index). You can recommit or fix things.

To unstage the changes too:

git reset --mixed HEAD~1

To discard the changes completely:

git reset --hard HEAD~1

🛰️ Option 2: Delete Last Commit That Has Been Pushed

⚠️ This rewrites history. Only do this if you’re sure others aren’t depending on the commit.

git reset --hard HEAD~1
git push origin main --force

Replace main with your branch name.


🧠 Understanding the Commands

CommandDescription
--softRemoves the commit, but keeps changes staged
--mixedRemoves the commit, unstages changes
--hardRemoves the commit and all changes
--forceOverwrites remote history (use with caution)

✅ Summary

GoalCommand
Delete last commit, keep changesgit reset --soft HEAD~1
Delete commit + unstage changesgit reset --mixed HEAD~1
Delete commit + discard changesgit reset --hard HEAD~1
Delete pushed commitgit reset --hard HEAD~1 && git push --force

🚀 Pro Tip

If you just want to change the commit message instead of deleting the whole commit:

git commit --amend

🏁 Conclusion

Deleting the last commit in Git is easy when you understand your intent: preserve changes, unstage them, or discard them entirely. Be extra cautious when working with pushed commits — especially on shared branches.

Sharing Is Caring:

Leave a Comment