Anthony
Anthony

Reputation: 35928

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 branch-x.

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?>

Upvotes: 3

Views: 1795

Answers (2)

ElpieKay
ElpieKay

Reputation: 30858

One possible solution is to use git cherry-pick. Suppose we have the commit graph like this.

A-B-C-D-E->branch-x
M-N->branch-y

Now you want CDE to be on branch-y.

git checkout branch-y
git cherry-pick C D E

or

git cherry-pick C^..E

and we get

M-N-C'-D'-E'->branch-y

Another possible solution is to use git rebase.

git rebase --onto branch_y C^ E
git branch -d branch_y
git checkout -b branch_y

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

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

Upvotes: 5

Related Questions