Replay the last N git commits on a different branch

GitVersion ControlCommit

Git Problem Overview


I accidentally made 10 commits on branch "testing" when I intended to commit them on branch "master". The other commits on the "testing" branch are garbage, so I don't want to merge it with "master". Instead, I just want to replay the last 10 commits on master.

Git Solutions


Solution 1 - Git

Rebase should do it.

git rebase -p --onto master testing~10 testing

This will copy the last ten commits on testing to master and make that the new testing (the old testing will be an orphan). Then you can merge master to testing as a fast-forward.

git checkout master
git merge testing

Solution 2 - Git

  1. git checkout master
  2. git whatchanged testing
  3. git cherry-pick _________

?

Solution 3 - Git

As said in comments, the rebase-inspired answer is leaving the 'garbage' commits orphaned.

Just use simple tools:

git checkout master
git merge testing
git checkout testing
git reset --hard HEAD~10   # Go back 10 commits (*1)
git checkout master

(*1) You will only be "losing" commits from the testing branch, since you'll have those commits in master thanks to the merge.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom LehmanView Question on Stackoverflow
Solution 1 - GitTalljoeView Answer on Stackoverflow
Solution 2 - GitRonView Answer on Stackoverflow
Solution 3 - GitTimView Answer on Stackoverflow