How to move (unpushed) commits from one branch to the other
I was on
branch-x and made few changes and committed them (but did not push). Although the commits were correct, they should not have been made in
branch-x but instead in
branch-y. How can I take the commits from
branch-x and apply them to
branch-y. I want to avoid pushing the committed changes from
Below is what I did in commands.
(branch-x)$: git status (branch-x)$: git add . (branch-x)$: git commit -m "some commit" <oops, I should have made these changes in branch-y> (branch-x)$: git checkout -b branch-y (branch-y)$: <how can I take the commit from branch-x and apply it here?>
2 Solutions collect form web for “How to move (unpushed) commits from one branch to the other”
Since you already created the branch you want via
git checkout -b branch-y, and this new branch has the commit you want, then the only remaining problem is an extra rogue commit on the tip of
branch-x. Since you did not publish
branch-x yet, you should be safe in rewriting that history. Do this:
git checkout branch-x # switch back to branch-x git reset --hard HEAD~1 # nuke the rogue commit on the tip of this branch
One possible solution is to use
git cherry-pick. Suppose we have the commit graph like this.
Now you want CDE to be on branch-y.
git checkout branch-y git cherry-pick C D E
git cherry-pick C^..E
and we get
Another possible solution is to use
git rebase --onto branch_y C^ E git branch -d branch_y git checkout -b branch_y