Rebase onto another branch and remove changes of old one

Issue

I have:

A--B             (master)
    \    
     C--D        (bad-branch)
         \
          E--F   (my-branch)

The result i want:

A--B             (master)
    \    
     E--F        (my-branch)

I tried rebase my-branch onto master but when i push my-branch to repo, it’s merged with the origin and the bad commits with the changes come back.

Solution

You can rebase a number of commits onto another branch using the --onto flag.

First make sure you have the branch checked out you want to rebase (not strictly necessary as you can provide that arg to rebase, but step-by-step is often clearer and easier).

git checkout my-branch
# or git switch my-branch

Rebase the top two commits onto master:

git rebase --onto master @~2

An alternative to counting the number of commits is to just use the bad branch name as a ref:

git rebase --onto master bad-branch

In your example @~2 on my-branch is the same commit as bad-branch so they could be used interchangeably.

Answered By – camh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published