Skip to content

Instantly share code, notes, and snippets.

@gringoh
Created May 13, 2020 14:06
Show Gist options
  • Save gringoh/3aad67c4320ca68acd0d7387ff7672f4 to your computer and use it in GitHub Desktop.
Save gringoh/3aad67c4320ca68acd0d7387ff7672f4 to your computer and use it in GitHub Desktop.
[git: Move commits to another branch] #git

Moving to an existing branch

If you want to move your commits to an existing branch, it will look like this:

git checkout existingbranch
git merge master         # Bring the commits here
git checkout master
git reset --keep HEAD~3  # Move master back by 3 commits.
git checkout existingbranch

The --keep option preserves any uncommitted changes that you might have in unrelated files, or aborts if those changes would have to be overwritten -- similarly to what git checkout does. If it aborts, git stash your changes and retry, or use --hard to lose the changes (even from files that didn't change between the commits!)

Moving to a new branch

This method works by creating a new branch with the first command (git branch newbranch) but not switching to it. Then we roll back the current branch (master) and switch to the new branch to continue working.

git branch newbranch      # Create a new branch, containing all current commits
git reset --keep HEAD~3   # Move master back by 3 commits (Make sure you know how many commits you need to go back)
git checkout newbranch    # Go to the new branch that still has the desired commits

Warning: after this it's not safe to do a rebase in newbranch without extra care. But do make sure how many commits to go back. Alternatively, instead of HEAD~3, you can simply provide the hash of the commit (or the reference like origin/master) you want to revert back to, e.g:

git reset --keep a1b2c3d4

WARNING: With Git version 2.0 and later, if you later git rebase the new branch upon the original (master) branch, you may need an explicit --no-fork-point option during the rebase to avoid losing the commits you moved from the master branch. Having branch.autosetuprebase always set makes this more likely. See John Mellor's answer for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment