I made a series of commits after a good commit on the master branch, which in hindsight I should have made in another branch. Can I move those commits, beginning with a specific commit, to another branch, and keep the good commit as the last commit on master?
Asked
Active
Viewed 5,372 times
17
-
1Possible duplicate of [Move the most recent commit(s) to a new branch with Git](http://stackoverflow.com/questions/1628563/move-the-most-recent-commits-to-a-new-branch-with-git) – Chris Kent Nov 25 '15 at 15:34
2 Answers
25
Sure:
$ git branch new-branch-name # Create a new branch from the current commit
$ git reset --hard <last good commit on master> # Reset master to the good commit

mipadi
- 398,885
- 90
- 523
- 479
-
So if I want to remove last two commits from master to another branch. I checkout last commit of master, make a branch from there and then reset master HEAD~2? This won't also remove the commits from the branch? Does this mean that the commits are not deleted just the master's pointer is now pointing two commits earlier? That is reset just moves branch pointer a number of commits earlier? – croraf Dec 10 '17 at 09:26
-
@croraf: The branch will still point to the previous two commits that were on master. – mipadi Dec 11 '17 at 18:57
1
Yes, you can, and that would be 2 separate operations:
Copy the commits from one branch to the branch you want them to be:
git cherry-pick <hash_of_commit> --onto <target_branch>
Then fix the master branch reverting to a good commit:
git checkout master
git reset --hard <hash_of_good_commit>

karlphillip
- 92,053
- 36
- 243
- 426