Skip to content

Instantly share code, notes, and snippets.

@gambitier
Created December 30, 2025 06:37
Show Gist options
  • Select an option

  • Save gambitier/db52ac39a69e8f7fbb310f85aede792b to your computer and use it in GitHub Desktop.

Select an option

Save gambitier/db52ac39a69e8f7fbb310f85aede792b to your computer and use it in GitHub Desktop.

πŸš€ Reset Git Commit History and Force Push to Remote

Sometimes you need to wipe your Git history β€” for example, to clean sensitive data or start fresh while keeping your current code.
This guide explains how to reset commit history safely and push changes to your remote repository.


⚠️ Warning

These operations rewrite Git history.
They are destructive and will break clones or forks that depend on your old commits.

Only do this if:

  • You are the only contributor, or
  • You have coordinated with your team.

🧹 Option 1: Start Fresh (Keep Code, Remove All History)

Use this when you want to keep your current files but erase all past commits.

# 1. Create a new orphan branch (no history)
git checkout --orphan latest_branch

# 2. Add all current files
git add -A

# 3. Commit the snapshot
git commit -m "Initial commit"

# 4. Delete the old branch
git branch -D main  # or 'master'

# 5. Rename the new branch to 'main'
git branch -m main

# 6. Force push to the remote repository
git push -f origin main

βœ… Result: A fresh repo with a single new commit β€” no previous history.


πŸ•“ Option 2: Remove Older Commits, Keep Recent Ones

Use this when you only want to remove older commits and keep the last few.

# Example: keep only the last 5 commits
git checkout main
git reset --hard HEAD~5
git push origin main --force

βœ… Result: Only the last 5 commits remain in history; older commits are gone from remote.


🌍 Option 3: Overwrite Remote with Local State

Use this if you want your remote to exactly mirror your local repository.

# Force push all local branches to remote
git push origin --force --all

βœ… Result: The remote repository is fully replaced by your local version.


🏷️ Optional: Clean Tags

To delete all remote tags and push local tags freshly:

# Delete all remote tags
git tag -l | xargs -n 1 git push --delete origin

# Push current tags (if any)
git push origin --tags

🧠 Summary

Goal Command(s)
Start completely fresh git checkout --orphan ... git push -f origin main
Keep only recent commits git reset --hard HEAD~N ... git push -f
Replace remote with local git push --force --all
Clean remote tags git tag -l | xargs -n 1 git push --delete origin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment