Home > Back-end >  How to rebase on to an earlier remote commit?
How to rebase on to an earlier remote commit?

Time:04-07

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?

CodePudding user response:

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.

CodePudding user response:

If I were in your position and my branch was in your state, I would use ypnos's answer of rebase --onto. This is because it's probably the most efficient one-liner and I'm comfortable doing it.

That being said, another thing you could do which may be conceptually a little simpler is to look at your reflog, find the commit your branch was on before the rebase, and put your branch back to how it was before the rebase:

git reset --hard <previous-commit-id>

Now it will be as if you didn't do the first rebase, and you can go ahead and redo it with the commit ID you intended to use in the first place.

  • Related