Move any Git commit from one branch to another
I have the following Git commits tree:
R - A - B - C - D (master)
I would like:
R - A - B - D' (master) \ - C (new-branch)
How could I do that (assuming it is even possible)?
I started using
git cherry-pick but I didn’t manage to remove the commit from the master branch.
4 Solutions collect form web for “Move any Git commit from one branch to another”
You cannot get exactly what you want since there will be differences in the commits, but the content of the files will be as you want if you do:
$ git checkout master $ git reset --hard sha1-of-B # set master back to B $ git cherry-pick sha1-of-D # set master to R-A-B-D' $ git checkout -b new-branch sha1-of-B # set new-branch to B $ git cherry-pick sha1-of-C # set new-branch to R-A-B-C'
Note that you do not really need to cherry-pick to set new-branch, and you could just as easily do:
$ git reset sha1-of-C
while you have new-branch checked out. This will actually give you R-A-B-C instead of R-A-B-C’. Note that the only difference between C and C’ is the commit time.
Once you do the reset, you may have a hard time locating the sha1 hashes of the various commits (they are available from the reflog), so you may want to put tags on everything before you begin, or store the history somewhere.
Avoid unnecessary cherry-picks by creating new-branch directly at C, and then simply rebase master to remove commit C:
git branch new-branch sha1-of-C git rebase --onto sha1-of-C^ sha1-of-C master
The second command deletes C from master by rebasing
master (“branch” in the git-rebase man page) commits starting from
sha1-of-C (“upstream”) onto the commit before
Or you can do the rebase interactively if that second command is too confusing:
git rebase -i sha1-of-C^
On the interactive rebase, simply delete commit C, save and quit.
During rebasing, if git complains about merge conflicts, resolve them,
git add, and
git rebase --continue. You would have to resolve these conflicts regardless of the method you choose.
git branch new-branch git reset --hard B git cherry-pick D git checkout new-branch git reset --hard C
A recipe that does not involve variables like B or sha1-of-C:
git checkout master if not already checked out.
git branch tempD # create temporary branch, pointing to D git branch new-branch HEAD^ # create new-branch, pointing to C git reset --hard HEAD^^ # reset master to B git cherry-pick tempD # apply D's changeset onto B git branch -D tempD # remove temporary branch