Search code examples
gitbranchrebase

Git rebase empty branch


Lets say I have taken a branch of main, called BR1.

I commit 3 changes to BR1 (c1, c2, c3).

I then take a branch of BR1, called BR2.

main ------> BR1 (c1) (c2) (c3) -----> BR2

I have now decided that I actually didn't want to branch BR2 from BR1, but instead I want BR2 to be branched from main ... i.e I don't want c1, c2, c3 on BR2

`main` ------> `BR1` (c1) (c2) (c3) 
       ------> `BR2`

Am I right in thinking I just need to rebase BR2 onto main?

git switch main
git pull
git switch BR2
git rebase -i main
git push -f

I tested this and it worked, but I was a little worried as the interactive rebase had

pick c1
pick c2
pick c3

which I had to change to

drop c1
drop c2
drop c3

So wasn't sure if something was going to break.

The other confusing thing for me was that BR2 has no commits on it, i.e when I made the BR2 branch, I made no commits to it, so I wasn't even sure if its valid to rebase an 'empty' branch?


Solution

  • If BR2 really has no commits of its own, you may simply do a hard reset to the main branch:

    # from BR2
    git reset --hard main
    

    If BR2 did have its own commits, then you could use a rebase onto:

    # from BR2, again
    git rebase --onto main c3