Search code examples
gitrebase

How to rebase on to an earlier remote commit?


I have a local commit A and I used git pull --rebase origin master, so now A is stacked on top of the latest remote master commit, but I realized that I didn't want to do that and needed to actually rebase on to an earlier vision of master.

I found the commit hash earlier_commit_hash associated with the earlier commit and did git pull --rebase origin earlier_commit_hash, but didn't seem to change anything (my local branch still includes all the remote master commits after earlier_commit_hash).

What is the proper way to accomplish what I need?


Solution

  • The newer commits from master are already part of your local history, this is why they will be carried over when you use rebase on the older commit. Note that they might still be rewritten with new hashes which makes the situation worse.

    You could try rebase --onto instead. From the manpage:

           A range of commits could also be removed with rebase. If we have the following situation:
    
                   E---F---G---H---I---J  topicA
    
           then the command
    
               git rebase --onto topicA~5 topicA~3 topicA
    
           would result in the removal of commits F and G:
    
                   E---H'---I'---J'  topicA
    
           This is useful if F and G were flawed in some way, or should not be part of topicA.
    

    So you can use the same mechanism to exactly cut-out all the commits between the reference on master and your branch-exclusive commits.