Wednesday, April 6, 2016

Rename a Remote Branch in Git

In the previous post I described how to rename a local branch in Git. Now let's take a look how to rename a remote branch. The process is a bit more complicated than with a local one and consists of the following steps:
  1. Create a new local auxiliary branch with the desired name.
  2. Push newly created local branch to the remote repository.
  3. Delete the original branch from the remote repository.
  4. Delete an auxiliary local branch (optional).
Let's take a look at a simple example. Suppose I have a Git repository which contains a couple of remote branches in it:
$ git branch -r
  origin/HEAD -> origin/master
  origin/master
  origin/release-v1.0
Suppose that branch release-v1.0 was created by mistake and I actually want it to be named release-v1.1. Let's perform the first step and create an auxiliary branch:
$ git branch release-v1.1 origin/release-v1.0
Let's see what we have locally and remotely:
$ git branch
* master
  release-v1.1
$ git branch -r
  origin/HEAD -> origin/master
  origin/master
  origin/release-v1.0
Now it is time to push our new local branch to the remote repository:
$ git push origin release-v1.1
The above command creates a new remote branch named after the local one created on the previous step:
$ git branch -r
  origin/HEAD -> origin/master
  origin/master
  origin/release-v1.0
  origin/release-v1.1
Let's delete the old remote branch:
$ git push origin :release-v1.0
Now we have the following remote branches:
$ git branch -r
  origin/HEAD -> origin/master
  origin/master
  origin/release-v1.1
Optionally we can get rid of the auxiliary local branch:
$ git branch -d release-v1.1
Let's take a look at the final result:
$ git branch
* master
$ git branch -r
  origin/HEAD -> origin/master
  origin/master
  origin/release-v1.1
Here are all the commands in one place for convenience:
$ git branch release-v1.1 origin/release-v1.0
$ git push origin release-v1.1
$ git push origin :release-v1.0
$ git branch -d release-v1.1

2 comments:

  1. And then you can't have a PR against it. Fun time this git is.

    ReplyDelete
    Replies
    1. By which I mean the original PR is against the old branch and not against the new. rename git does not support. nice, not really.

      Delete