Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detach a branch and reattach it to some different branch in Git

Tags:

git

I have a master and topic branch forked from it as shown below:

A---B---C---D master
     \
      E---F topic

I want to detach this topic branch and attach it to my feature branch like shown below:

G---H---I---J feature
             \
              E---F topic

Here master and feature branches are present on both remote and local while the topic is only at my local. I want to push topic after reattaching it to feature.

Thanks

like image 920
Rajat Srivastava Avatar asked Jul 27 '16 10:07

Rajat Srivastava


People also ask

How do I pull a branch into another branch?

After running the stash command for a branch, if the git user wants to pull the branch's changes to another branch, it can be done easily by using the `git stash pop` command that works like the `git merge` command.

How do you reattach a detached head?

Now, the best way to reattach the HEAD is to create a new branch. We can do it as simple as git checkout -b <branch-name> . This will commit the changes from your temporary branch into the branch you need them.

How do you push changes from detached head to branch?

If you want to keep changes made with a detached HEAD, just create a new branch and switch to it. You can create it right after arriving at a detached HEAD or after creating one or more commits. The result is the same. The only restriction is that you should do it before returning to your normal branch.


1 Answers

If feature contains B, then it's as simple as git rebase feature from the topic branch. If this is not the case, you'll need:

git rebase --onto feature B

The difference is because if B is not contained in feature, the rebase command won't know how far to wind back before replaying.

In general, git rebase --onto X Y means "replay all commits after Y on top of X". git rebase X is shorthand that first finds the common ancestor of HEAD and X (Z = git merge-base HEAD X), then replay all commits after Z on top of X.

Docs: https://git-scm.com/docs/git-rebase

like image 137
cmbuckley Avatar answered Nov 15 '22 00:11

cmbuckley