0
0
GitHow-ToBeginner · 3 min read

How to Undo Git Push: Simple Commands to Fix Mistakes

To undo a git push, you can use git reset to move your branch back and then force push with git push --force. This removes the pushed commits from the remote repository. Be careful with force push as it rewrites history and can affect others.
📐

Syntax

Use the following commands to undo a git push:

  • git reset --hard <commit_hash>: Moves your local branch to a previous commit, discarding later commits.
  • git push --force: Updates the remote branch to match your local branch, overwriting history.

Replace <commit_hash> with the commit you want to go back to.

bash
git reset --hard <commit_hash>
git push --force
💻

Example

This example shows how to undo the last pushed commit:

  1. Find the commit before the last one using git log.
  2. Reset your branch to that commit.
  3. Force push to update the remote.
bash
git log --oneline
# Output shows commits, for example:
# 9f8e7d6 Add feature
# a1b2c3d Fix typo

# Undo last commit:
git reset --hard 9f8e7d6
git push --force
Output
# git log --oneline output: 9f8e7d6 Add feature a1b2c3d Fix typo # After reset and force push, remote branch matches commit 9f8e7d6
⚠️

Common Pitfalls

Force pushing can overwrite changes others have pulled, causing conflicts. Always communicate with your team before using git push --force. Avoid undoing pushes on shared branches like main unless necessary.

Another mistake is resetting without specifying the correct commit hash, which can cause loss of work.

bash
git reset --hard HEAD~1  # Correct: undo last commit

git push --force          # Force update remote

# Wrong: forgetting force push leaves remote unchanged
git reset --hard HEAD~1
git push                 # This will fail or not undo remote commit
📊

Quick Reference

CommandPurpose
git reset --hard Move local branch to a previous commit, discarding newer commits
git push --forceOverwrite remote branch to match local branch
git log --onelineView commit history in short form
git reset --soft Undo commits but keep changes staged (alternative)

Key Takeaways

Use git reset --hard with a commit hash to move back locally.
Force push with git push --force to update the remote branch.
Always check commit history with git log before undoing.
Communicate with your team before force pushing to avoid conflicts.
Avoid undoing pushes on shared branches unless absolutely necessary.