How to Delete Specific Commits Without Breaking Later Changes Using Git Rebase
When refactor and business changes share a branch, you can safely remove unwanted refactor commits by interactively rebasing onto the last good commit and force‑pushing, ensuring later business commits remain intact.
Background : A development branch contains both refactor commits and business feature commits. Because the refactor work is no longer needed, the unwanted refactor commits must be removed without affecting subsequent business commits.
Problem : Given a commit history (from newest to oldest) D (business commit), C (refactor), B (refactor), A (base), the goal is to delete commits B and C while preserving D.
Solution :
Identify the commit immediately before the first unwanted commit (commit A in the example).
Run an interactive rebase starting from that commit: git rebase -i A This opens the editor with a list of commits.
In the editor, change the word pick to drop for the lines corresponding to commits B and C, then save and exit.
After the rebase completes, force‑push the rewritten history to the remote repository: git push --force The two refactor commits are now removed, and the later business commit D remains unchanged.
Note : Force‑pushing rewrites public history; ensure no other collaborators rely on the original commits or coordinate with the team before executing the push.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaEdge
First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
