Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to rename remote branch in Git

📅 2017-Oct-12 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ branch, git ⬩ 📚 Archive

Git is known for its confusing and difficult commands. If you want to rename a remote branch, say a branch that is on Github, from the comfort of your shell then you are in luck for one such experience!

This is the invocation to rename a branch old_branch on a remote named foo_remote to a new branch name new_branch:

$ git push foo_remote foo_remote/old_branch:refs/heads/new_branch :old_branch

If you find yourself renaming remote branches a lot, then it is better to add this as a Git command. To do that, save this piece of shell script code as a file named git-rename-remote-branch:

#!/bin/sh

# From: https://github.com/sschuberth/dev-scripts/

if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : $(basename $0) <remote> <old name> <new name>"
    echo "Example   : $(basename $0) origin master release"
    exit 1
fi

git push $1 $1/$2:refs/heads/$3 :$2

The file can be named anything as long as it begins with a git- prefix. Make it executable and place it in any directory that is in your PATH.

Now, you can rename a remote branch with a saner command:

$ git rename-remote-branch foo_remote old_branch new_branch

Tried with: Git 2.7.4 and Ubuntu 14.04


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧