How to Revert the Previous Commit in Git

Whether you’ve committed the wrong changes or simply changed your mind, Git offers flexible tools to revert or undo the previous commit—without losing control of your project history.

In this guide, we’ll cover several ways to undo the last commit in Git depending on your use case: whether the commit was pushed, unpushed, or needs to be amended.


✅ Option 1: Revert a Commit (Safe & History-Preserving)

Use this when the commit has already been pushed and shared with others.

git revert HEAD
  • This creates a new commit that undoes the changes made in the previous one.
  • Ideal for public/shared branches.

💡 Use this when you do not want to rewrite history.


✅ Option 2: Amend the Last Commit (Modify Message or Add Files)

If you want to fix the most recent commit (e.g., add a file or change the message), use:

git commit --amend

You’ll be able to:

  • Edit the commit message
  • Include newly staged changes

💡 Only use this if the commit has not been pushed or you’re sure others aren’t affected.


✅ Option 3: Delete the Last Commit (Unpushed Only)

If you want to completely remove the last commit and it’s not yet pushed:

git reset --hard HEAD~1
  • HEAD~1 refers to one commit before the latest.
  • --hard resets both your working directory and index (⚠️ discards changes).

Other variants:

  • Keep changes in working directory: git reset --soft HEAD~1
  • Keep changes unstaged: git reset --mixed HEAD~1

⚠️ Don’t use reset on commits that have already been pushed to shared branches — it rewrites history and can cause issues for collaborators.


🔍 Bonus: Find Commit History with Git Log

Run:

git log --oneline

To see recent commits and identify the one you want to revert, reset, or amend.


✅ Summary

TaskCommandUse Case
Revert last commit safelygit revert HEADShared branches (safe, new undo commit)
Amend previous commitgit commit --amendUnpushed changes (e.g., edit message)
Remove last commit (delete history)git reset --hard HEAD~1Local/unpushed only (dangerous)
Keep changes after removing commitgit reset --soft HEAD~1Rewind commit but keep staged files
View commit historygit log --onelineReview what to revert/reset

🚀 Final Thoughts

Git gives you powerful options to undo, rewrite, or reverse your commits—each suited for different development scenarios. When in doubt, use git revert for a safe, history-preserving undo, especially on collaborative projects.

Sharing Is Caring:

Leave a Comment