Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving commits from one branch to another

I've committed a bunch of changes onto the master branch of my git repository, and pushed it upstream (although I'm the only one working out of these.) What I want to do is to pull these last few commits off, roll back master to before the pulled-off commits, re-apply the commits onto the develop branch, and then merge back onto master.

Here's what my repository looks like now:

a [master] [remotes/origin/master]
|
b
|
c
|
d (merge branch 'develop')
|\
| \
|  e [develop] [remotes/origin/develop]
|  |
q  f
|  |
r  g

And here's what I want it to look like:

Z [master] [remotes/origin/master]
|\
| \
|  A
|  |
|  B
|  |
d  C
|\ |
| \|
|  e [develop] [remotes/origin/develop]
|  |
q  f
|  |
r  g

Can I get some help on this? I'm thinking this is a job for rebase, but I'm not quite sure how to make it happen.

like image 618
Doug Avatar asked Nov 08 '10 03:11

Doug


People also ask

Can I move commits from one branch to another?

If you want to move commits to an existing branch you need to merge your changes into the existing branch before executing git reset --hard HEAD~3 (see Moving to an existing branch above). If you don't merge your changes first, they will be lost.

How do I move multiple commits from one branch to another?

You can do this with multiple commits too, just cherry pick several, then reset back to the last commit you want to keep. The process is the same if you have committed to local master by mistake - just cherry-pick to a branch, then reset master. Only ever do this if you haven't pushed the commits to origin.

How do you move pushed commits to another branch?

Undo and Commit to New Branch Use git log to check how many commits you want to roll back. Then undo the commits with git reset HEAD~N where “N” is the number of commits you want to undo. Then create a new branch and check it out in one go and add and commit your changes again.

Can a commit be taken from one branch and move to a different branch in git?

You can move commits from one branch to another branch if you want changes to be reflected on a different branch than the one to which you pushed the changes.


1 Answers

Here you are:

# move cba onto e
git branch foo
git rebase --onto <SHA1-e> <SHA1-d> foo

# rewind master to d
git checkout master
git reset --hard <SHA1-d>

# merge
git merge foo

You might want to pick a more descriptive branch name than foo, since it'll be recorded in the merge commit message for Z.

like image 176
Cascabel Avatar answered Sep 17 '22 12:09

Cascabel