131

Is there a way to rename a Git branch locally and push it to the remote branch, even if there are already many commits pushed to the remote branch?

Or, is it necessary to create a new local branch, delete the old local branch, and then repeat the operation on the remote repository?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Rémi Becheras
  • 14,902
  • 14
  • 51
  • 81

1 Answers1

225

Yes,

the feature move exists to rename the branch locally

git branch --move <old_name> <new_name>

but to push it, you must delete the old and push the new

git checkout <new_name>
git push origin [--set-upstream] <new_name>
git push origin --delete <old_name>

--set-upstream is optional, it configure the new local branch to track the pushed one

You can use the following shorthands:

  • move locally (--move) :

      git branch -m <old_name> <new_name>
    
  • push new branch (--set-upstream, optional) :

      git push origin [-u] <new_name>
    
  • delete (--delete) :

      git push origin -d <old_name>
    

NB.

Thanks to torek's comment:

Worth mentioning, by the way, is that you should

  1. notify other users who share the upstream that you will be doing this, and
  2. do this in the order shown (set new name, then delete old).

The reason for #1 is that those users will need to adjust.

The reason for #2 is mainly just efficiency: it avoids having to re-copy objects to an upstream repo that drops commits on branch deletion (most bare repositories do that, and most repositories that accept pushes are bare)

Community
  • 1
  • 1
Rémi Becheras
  • 14,902
  • 14
  • 51
  • 81
  • 4
    Very minor. I believe you're confusing deleting a branch locally with `branch -D` with the remote shorthand. But no such `-D` option exist as shorthand for `--delete` in the latest git (git version 2.14.+), rather it is the lowercase `-d`. So it should be `git push origin -d ` – Novice C Sep 27 '17 at 02:39
  • If you have an Open PR (on GitHub for example) with the `` it will get closed when you delete the remote branch, so you will need to create a new one, since there is no way (at the time) to change the branch a PR is based upon (you can only change the destination). – Martin Marconcini Feb 21 '18 at 21:21
  • An even more terse way to delete a remote branch is `git push origin :[old_branch_name]`. – occasl Mar 08 '19 at 01:12
  • For some remotes (e.g. Bitbucket), before the last step (`--delete`), you need to "unassign" the branch as the "default" branch of the repo – Janaka Bandara May 02 '21 at 12:03