如何执行git reset --soft <some-commit>并绕过Git合并提交?
Let’s break down how to achieve your goal—getting your some branch to retain changes from C2, C4, and C5 without including the merge commit M3 (and its C3 changes)—using reliable, straightforward methods.
Understanding the Initial Issue
When you run git reset --soft C1 on the some branch, Git moves the branch pointer back to C1 but keeps all cumulative changes from C2, M3, C4, and C5 in your staging area. This includes the changes from C3 (since M3 merged it), which is exactly what you want to avoid. Instead of untangling those mixed changes, it’s cleaner to rebuild the branch history with only the commits you need.
Method 1: Interactive Rebase (Best for Full Control)
Interactive rebase lets you manually edit your commit history, making it easy to skip the merge commit entirely:
- Checkout your
somebranch:git checkout some - Start an interactive rebase starting from C1:
git rebase -i C1 - A text editor will open listing all commits on
someafter C1. You’ll see lines like:pick <hash> C2 merge <hash> <hash> M3 pick <hash> C4 pick <hash> C5 - Delete the line corresponding to the merge commit
M3. Save and close the editor. - Git will now reapply C2, C4, and C5 onto C1. You may encounter conflicts when applying C4 or C5 (since they were originally built on M3’s merged state). Resolve these by keeping your changes from C4/C5 and discarding any references to C3’s code.
- Once conflicts are fixed, continue the rebase:
git rebase --continue
When finished, your some branch will have a clean history: C1 → C2 → C4 → C5.
Method 2: Cherry-Pick Commits onto a Fresh Branch
If you’d rather avoid altering the original some branch first, create a new branch and cherry-pick only the commits you want:
- Create a new branch starting at C1:
git checkout -b new-some C1 - Cherry-pick the commits you want to retain (C2, then C4, then C5):
You might face conflicts when cherry-picking C4/C5—resolve them by prioritizing your changes over C3’s.git cherry-pick C2 git cherry-pick C4 git cherry-pick C5 - Replace the original
somebranch with this new one (optional):git checkout some git reset --hard new-some git branch -d new-some
Key Notes
- Both methods rewrite the history of the
somebranch. If you’ve pushed this branch to a remote repository, you’ll need to usegit push --force(orgit push --force-with-leasefor safer overwriting). - Conflict resolution is normal here—since C4 and C5 were built on top of the merged M3 state, Git will flag any parts of those commits that depend on C3’s changes. Just edit the files to keep only the code you want from C2, C4, and C5.
内容的提问来源于stack exchange,提问作者ktretyak

