64

I have started doing some work on a branch which I have in term realised was the wrong branch. Is there a way to move a branch to a different branch.

For example:

A -- B -- C -- D -- HEAD
 \-- E -- F -- G -- H -- I -- J
      \-- K -- L

And I want this:

A -- B -- C -- D -- HEAD
 \    \-- K -- L
  \
   \-- E -- F -- G -- H -- I -- J
0

3 Answers 3

102

Let's say you've named your branches like so:

    A -- B -- C -- D (master)
     \-- E -- G -- H -- I -- J (current-parent)
          \-- K -- L (my-branch)

What you want to do is rebase my-branch onto the B commit like so:

    git rebase current-parent my-branch --onto B
4
  • 6
    This answer should have been accepted ! Thanks a lot Commented Dec 13, 2018 at 8:31
  • Thanks for the pretty picture
    – Rob
    Commented Nov 28, 2022 at 20:51
  • 1
    the --onto B, where B is a commit, can also use a branch name, if you want to rebase to the tip of that branch.
    – colm.anseo
    Commented Jun 8, 2023 at 19:37
  • @colm.anseo if you want to rebase to the tip of a branch (eg. master), you wouldn't need --onto anymore, right? You would just do git checkout my-branch && git rebase master. Or am I missing something? Commented Aug 7, 2023 at 7:41
35

You could use git rebase --onto, e.g.,

git rebase --onto new-base old-base your-branch

So in your case, something like:

git rebase --onto B E L

should work.

1
  • thank you for naming the options. Very confused until seeing this. Commented Feb 18, 2022 at 19:35
2

This is just the sort of thing git rebase can do.

https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.