DEV Community

Mohamed Idris
Mohamed Idris

Posted on

How to Move a Git Branch to a Different Parent

You branched off feature-A, did your work, then realized your branch should have been based on main instead. Now your branch carries all of feature-A's commits along with yours.

Here's how to fix it in 4 steps.

The Problem

main ---- A ---- B
                  \
                   feature-A ---- C ---- D
                                          \
                                           your-branch ---- E  <-- your commit
Enter fullscreen mode Exit fullscreen mode

You only want commit E, but your branch includes C and D from feature-A.

The Fix

1. Find your commit hash

git log --oneline your-branch --not main
Enter fullscreen mode Exit fullscreen mode

This lists all commits on your branch that aren't in main. Identify yours — in this case, E.

2. Create a clean branch from main

git checkout main
git pull origin main
git checkout -b your-branch-clean
Enter fullscreen mode Exit fullscreen mode

3. Cherry-pick your commit

git cherry-pick <commit-hash>
Enter fullscreen mode Exit fullscreen mode

This applies only your commit on top of main.

4. Replace the old branch

git branch -D your-branch
git branch -m your-branch-clean your-branch
git push origin your-branch --force-with-lease
Enter fullscreen mode Exit fullscreen mode

Result

main ---- A ---- B
                  \
                   your-branch ---- E
Enter fullscreen mode Exit fullscreen mode

Clean branch, no extra baggage.

Why cherry-pick over rebase?

When your branch has merge commits and commits from another feature branch mixed in, git rebase can get messy — conflicts from commits that aren't even yours. Cherry-pick lets you grab exactly what you need and skip everything else.

Quick reminder

  • Use --force-with-lease instead of --force — it won't overwrite the remote if someone else pushed to your branch.
  • If you have multiple commits to move, cherry-pick accepts a range: git cherry-pick A^..B.

Top comments (0)