How to Revert the Last Commit in Git After a Push: A Step-by-Step Guide

Accidentally pushing a commit with mistakes or unwanted changes can happen. Fortunately, Git provides ways to safely undo or revert that last commit even after it has been pushed to the remote repository.

This guide explains how to revert your last pushed commit with different methods, depending on whether you want to keep or remove the changes from your project history.


Important Considerations Before You Proceed

  • Communicate with your team before rewriting shared history.
  • Understand the difference between reverting and resetting commits.
  • Always backup your current work if you’re unsure.

Method 1: Revert the Last Commit (Safe for Shared Repos)

If you want to undo the effects of the last commit without rewriting history, use git revert. This creates a new commit that reverses the changes introduced by the last commit.

Steps:

git revert HEAD
git push origin branch-name
  • Replace branch-name with your branch name (e.g., main).
  • This method is safe because it doesn’t alter the commit history; it simply adds a new commit that undoes the previous one.

Method 2: Remove the Last Commit by Resetting (Rewrite History)

If you want to completely remove the last commit from the history (e.g., if it contains sensitive data), you can reset your local branch and force-push the change.

Steps:

git reset --hard HEAD~1
git push --force origin branch-name
  • HEAD~1 moves the branch pointer back by one commit.
  • Warning: Force-pushing rewrites history and can disrupt collaborators who have pulled the original commit.

Method 3: Undo Last Commit but Keep Changes Locally

If you want to undo the last commit but keep your changes in the working directory (to fix and recommit), use:

git reset --soft HEAD~1

Then, you can modify your files and create a new commit.


Summary of Commands

GoalCommandNotes
Undo last commit safelygit revert HEAD + git pushKeeps history intact, safe for teams
Remove last commit and rewrite historygit reset --hard HEAD~1 + git push --forceUse with caution, rewrites history
Undo last commit but keep changesgit reset --soft HEAD~1Keeps changes for editing

Final Advice

  • Prefer git revert on shared branches to avoid conflicts.
  • Use force push (--force) only if you understand the risks.
  • Always double-check the branch name before pushing.
Sharing Is Caring:

Leave a Comment