2

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?>
Anthony
  • 33,838
  • 42
  • 169
  • 278
  • Your example shows you creating a *new* `branch-y`, rather than working on an *existing* `branch-y`; is that what you intend? – torek Jun 17 '16 at 02:39
  • yes, that is intended. – Anthony Jun 17 '16 at 02:39
  • Possible duplicate of [Move the most recent commit(s) to a new branch with Git](https://stackoverflow.com/questions/1628563/move-the-most-recent-commits-to-a-new-branch-with-git) – Robin Green Oct 19 '18 at 08:23

2 Answers2

5

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I would recommend cherry picking over reset --hard. It is safer. – Edvin Jun 17 '16 at 06:52
  • @Edvin I think you misunderstood the original problem. Branch `branch-y` already has the commits he wants. He only needs to remove the unwanted commit from `branch-x`. I originally answered using `git cherry-pick` but then revised it. – Tim Biegeleisen Jun 17 '16 at 06:55
  • Oh, okey. This comment "How can I take the commits from branch-x and apply them to branch-y." is a bit miss leading then. – Edvin Jun 17 '16 at 10:47
  • @Edvin Yup. My first answer used `cherry-pick`, and I edited it after the comment by @torek was addressed. – Tim Biegeleisen Jun 17 '16 at 10:50
1

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
ElpieKay
  • 27,194
  • 6
  • 32
  • 53