How to move a branch in git?

“Moving a branch” may mean two things:

1. Move the contents (the commits, the changes) associated with a branch name somewhere else in the repository.

2. Move the branch name (not the code changes!) to point to some other commit.

Let’s examine the two possibilities in detail:

1. Move branch contents and name:

This case is more complicated. If that’s what you want to do then “git rebase” is your friend. This command is quite complex and I suggest you study the git rebase help page before using it (‘git help rebase’).

 

Just to give you a quick example:

If your tree looks like this:

---o---o---o---o master
    \
      o---o---o---o---o next
                        \
                          o---o---o topic

And you want to move topic (all 3 commits associated with this branch) to master, then this command will do it:

git rebase --onto master next topic

This basically means “put onto ‘master’ everything between ‘next’ (not inclusive) and ‘topic’ (inclusive)”

After doing this your tree will look like this:

---o---o---o---o master
   |            \
   |              o´--o´--o´ topic
    \
      o---o---o---o---o next

2. Move just branch name

To move just the branch name type:
git pull  .  +new_br:old_br
What the above will do is within our local repository (the .)  move the branch old_br (just the branch name or label, not the contents) to the same location as branch new_br. In other words after this command old_br will point to the same commit as new_br.

Note that by doing this you may lose (easy) access to the commit where old_br used to point to and to all unreferenced commits below it – because you are essentially removing its association with that commit and if nothing else (another branch or tag) points to it AND if it is the last commit on that branch then the whole branch will disappear.

Here’s some examples to illustrate this:

---o---o---o---o master
    \
      o---o---o---o---o old_br
                        \
                          o---o---o some_br

OK, because there is another branch (some_br) above old_br.

---o---o---o---o master
    \
      o---o---o---o---o  old_br | [some_tag]

OK – there is also a tag (some_tag) at the same commit as old_br.

---o---o---o---o master
    \
      o---o---o---o---o old_br

NOT OK – old_br is the last commit on this branch and the entire branch (all the red dots) will disappear if old_br is moved. If this is not your intention then add another branch or tag there before moving old_br.

2 thoughts on “How to move a branch in git?

Leave a Reply

Your email address will not be published. Required fields are marked *