Accidentally pushing unwanted changes to a Git repository can happen to anyone. Whether it’s a bug, sensitive data, or just an incomplete feature, knowing how to undo or revert the last push safely is crucial.
This guide covers multiple methods to revert the last push in Git, depending on whether you want to undo the commit history, keep changes locally, or create a new commit that cancels previous changes.
Important: Before You Proceed
- Undoing pushed commits affects the shared history.
- Coordinate with your team to avoid disrupting others’ work.
- Always backup your current work if unsure.
Method 1: Revert the Last Commit With a New Commit (Safe for Shared Repositories)
If you want to undo the changes introduced by the last commit but keep the history intact, use git revert
. This creates a new commit that reverses the previous commit’s changes.
git revert HEAD
git push origin branch-name
- Replace
branch-name
with your branch (e.g.,main
). - This is the safest option for shared repos because history remains unchanged.
Method 2: Reset to the Previous Commit and Force Push (Rewrite History)
If you want to completely remove the last commit from history and you are sure it’s safe (e.g., you’re the only one working on the branch), use:
git reset --hard HEAD~1
git push --force origin branch-name
HEAD~1
means “one commit before the current HEAD.”- Warning: This rewrites history and can cause issues if others already pulled the commit.
- Use force push (
--force
) carefully.
Method 3: Undo Last Push but Keep Changes Locally
If you want to undo the push but keep the changes unstaged in your working directory:
git reset HEAD~1
git push --force origin branch-name
- This removes the last commit from history but keeps your files intact for further editing.
Summary of Commands
Goal | Command | Notes |
---|---|---|
Revert last commit safely | git revert HEAD + git push | Adds a new commit that undoes changes |
Remove last commit from history | git reset --hard HEAD~1 + git push --force | Rewrite history — use with caution |
Undo push but keep changes locally | git reset HEAD~1 + git push --force | Changes unstaged, history rewritten |
Final Tips
- Prefer
git revert
on shared branches to avoid conflicts. - Use force push only if you understand the consequences.
- Communicate with your team to prevent disrupting their workflow.