DEV Community

loading...

Rename Local and Remote Git Branch

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・1 min read

If you mistyped or want to change a branch name, here is the steps you should follow:

  1. Rename the local branch to the new name:

    $ git branch --move <old_branch_name> <new_branch_name>
    
  2. Delete the old branch on the remote:

    $ git push <remote> --delete <old_branch_name>
    
  3. Push the new branch to remote:

    $ git push <remote> <new_branch_name>
    
  4. Reset the upstream branch for the new_branch_name local branch

    $ git push <remote> -u <new_branch_name>
    

Example

If you would like to see all in action:

$ git branch -m bug feature
$ git push origin --delete bug
$ git push origin feature
$ git push origin -u feature

We renamed our bug branch to feature. Since you know all bugs are features in some way.

As Function

You may want to use it as a function like me:

#!/bin/bash
# $HOME/.functions

rename-git-branch() {
    OLD_NAME="$1"
    NEW_NAME="$2"

    git branch -m $OLD_NAME $NEW_NAME && \
    git push origin -d $OLD_NAME && \
    git push origin $NEW_NAME && \
    git push origin -u $NEW_NAME
}

Usage:

$ rename-git-branch bug feature

All done!

Discussion (0)

pic
Editor guide