Git History Cleanup Guide
This guide explains how to remove specific commits from Git history while preserving later commits.
Current Situation
Initial repository state has 4 commits:
4. abcd (latest)
3. abcc
2. abcb
1. abca (oldest)Objective
Remove commits abca and abcb while preserving abcc and abcd.
Instructions
1. Start Interactive Rebase
git rebase -i HEAD~42. Edit Rebase File
When your editor opens, you'll see something like this:
pick abca first commit
pick abcb second commit
pick abcc third commit
pick abcd fourth commitChange it to:
drop abca first commit
drop abcb second commit
pick abcc third commit
pick abcd fourth commit3. Save and Complete
- Save the file and close your editor
- Git will automatically process the rebase
4. Push Changes
If this is a local-only repository:
git pushIf you've already pushed these commits to a remote repository:
git push --force⚠️ Important Warnings
- This operation rewrites Git history
- Using
--forcepush can be dangerous in shared repositories - Always backup your repository before performing history-altering operations
- Coordinate with your team before modifying shared history
Best Practices
- Make sure you have no uncommitted changes before starting
- Create a backup branch before proceeding:
git branch backup-before-rebase - Inform team members before force pushing to shared repositories
- Consider using
git push --force-with-leaseinstead of--forcefor added safety
Troubleshooting
If something goes wrong during the rebase:
- To abort the rebase:
git rebase --abort - To restore from backup:
git checkout backup-before-rebase