Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove commits from git rebased branch after other commits were done

Tags:

git

rebase

revert

I have a project with two branches called master and feature/x. On feature/x I'm working on new features that will be merged on master.

For mistake on feature/x a rebase action based on master was done and pushed. Besides other commits were done and pushed on feature/x.

So I have two branches that contain "same commits" marked by different hash.

A -- B -- C -- D [master]
 \
  E -- F -- G -- H -- I [feature/x]

where C and D on master are respectively the same commits (rebased) of F and G on feature/x.

I would like to remove F and G from feature/x maintaining H and I. How can I do it?

I'm thinking to revert commit

git revert F G

from feature/x but those useless (duplicate) commits will remain in the history. I would know if there are better way to do it?

like image 357
bato Avatar asked Dec 06 '25 08:12

bato


1 Answers

The simplest way is to rebase interactively: checkout feature/x, and do

git rebase -i E

then just delete the lines for F, G from the rebase script you're prompted to edit. This will create leave your branches looking like

master   -> A -- B -- C -- D
                  \
feaure/x ->        E -- H' -- I'
                    \
(orphaned)           F -- G -- H -- I

You can do the same thing with

git rebase --onto E G feature/x

but the interactive method is much easier to remember (I had to look up the argument order in the online help).


Note that the old commits still exist, and are recoverable, but will eventually be garbage-collected if nothing refers to them.

like image 87
Useless Avatar answered Dec 08 '25 01:12

Useless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!