Problem: You rebased a branch (featureA
) and now need to rebase a branch that depends on it (featureB
).
Solution: Use git rebase --onto
, which takes three parameters:
- The branch name of
featureA
- The commit ID of the last commit in
featureA
, in the "old" log/history offeatureB
- (optional) The branch name of
featureB
There are to ways to get the "old" commit ID of the last commit in featureA
: the commit history of featureB
or the reflog.
First, check out the branch for featureB
and look at the log for featureB
. You can look for one of two things:
- How many commits are in
featureB
until you see the commits offeatureA
? - What is the commit ID of the last commit in
featureA
?
When counting the number of commits in featureB
, you can use the tilde notation to reference "earlier" commits.
Example 1: Using the number of commits in featureB
to reference to the last commit in featureA
, featureB
has 5 commits in this example:
git rebase --onto featureA featureB~5
If you have more than one commit in featureB
, you should use the tilde notation and not the caret notation, (feature^5)
, because the caret notation is for addressing commit IDs of merged branches. See the following articles explaining the differences in the notation for Git's rev-parse
- https://stackoverflow.com/questions/2221658/what-is-the-difference-between-head-and-head-in-git
- https://berkkaraal.com/notes/git/tilde-and-caret/
Example 2: You have the commit ID of the last commit in featureA
:
git rebase --onto featureA old-commit-id-of-featureA
Example 3: You have checked out a different branch entirely and still want to do the rebase from that branch (3rd parameter is no longer optional):
git rebase --onto featureA old-commit-id-of-featureA featureB
You can use this, where you just have rebased/changed featureA
. In this case, the Git reflog has recorded (at least) two commit IDs for featureA
:
featureA@{0}
(or justfeatureA
) is the most recent commit ID offeatureA
featureA@{1}
is the version offeatureA
before the rebase.
Example 4: Using the reflog:
git rebase --onto featureA featureA@{1} featureB
Sources: