Search code examples
gitrebasegit-rebase

Rebase without removing old branch


I have the following situation in Git:

A--B--C--D--E--F--G
       \--H--I

I want to rebase the branch, but keep the original branch. So I want this:

A--B--C--D--E--F--G
       \--H--I     \--H'--I'

The reason is that it's possible that my rebased branch will break things. If it does too much, and I can't easily fix it, I want to keep working with the old branch.

This is in a situation where the master branch is actually based on another repository and is a long way behind the original repository. I'm trying to get our (H-I) branch back up to the latest version of the original master branch.


Solution

  • Just create a new branch an work on it.

    git checkout your-old-branch
    git checkout -b to-be-rebased
    git rebase master
    

    and work on to-be-rebased until you have something workable.

    So your-old-branch still points to the same exact commit, unaffected.


    ...and the two first checkout steps can be combined into one (as pointed out by Johnathon) to avoid an unnecessary check out step :

    git checkout -b to-be-rebased your-old-branch
    

    Lastly, to be fair to Lasse's comment, it's true that we could have proceeded with cherry-pick to the same effect :

    git checkout -b new-branch master
    git cherry-pick master..your-old-branch