DEV Community

Ayush Poddar
Ayush Poddar

Posted on • Originally published at poddarayush.com

How to rename a Git branch (in remote too)

This post is part of my "Shorts" series, where each post is concise and hyper-focused on a single concept.

You may be working on a feature named good-feature. As you work on it, an inspiration strikes and you decide to rename your feature as unicorn-feature. To keep things consistent, you want to rename your feature branch from good-feature to unicorn-feature. You might already be deep into development and pushed quite a few changes to remote.

In this post, I will tell you:

  1. How to rename a branch in your local Git repository?
  2. How to rename the corresponding branch in remote?

Renaming local Git branch

The command is:

git branch --move <old-name> <new-name>
Enter fullscreen mode Exit fullscreen mode

In our example, the command would be:

git branch --move good-feature unicorn-feature
Enter fullscreen mode Exit fullscreen mode

How do you rename the branch in remote too?

You simply treat the branch - with the new name - as a new branch, and push the branch to remote.

git push --set-upstream origin <new-name>
Enter fullscreen mode Exit fullscreen mode

In our case, the command would be:

git push --set-upstream origin unicorn-feature
Enter fullscreen mode Exit fullscreen mode

This will create a new branch in our remote (origin) named unicorn-feature. However, the old branch still remains in remote. To verify, you can run the git branch --all to list all the branches - including the ones in remote. The next step, then, is to delete the old branch (good-feature) from remote.

Deleting the old branch from remote

In an earlier post about Git tags, I had written about the following command:

git push <remoteName> --delete <gitReference>
Enter fullscreen mode Exit fullscreen mode

In our case, we need to run:

git push origin --delete good-feature
Enter fullscreen mode Exit fullscreen mode

If the branch is being used by other collaborators too, then be careful about renaming the branch in remote. After the rename, they too should configure their local repositories to use the new branch.

Final words

Since now, you won't be stuck with a branch name once chosen. You can always rename it later.

References

Top comments (1)

Collapse
 
bobbyiliev profile image
Bobby Iliev

Great post! Well done!