DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Rename Local and Remote Git Branch

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Usage:

$ rename-git-branch bug feature
Enter fullscreen mode Exit fullscreen mode

All done!

Discussion (0)