Working with Git presents software developers with a powerful version control tool combining flexibility and convenience. A cornerstone of using Git is the ability to create branches that contain copies of the code repository, allowing changes to be made without disruption to the overall system. Renaming branches can be done locally and remotely, making it possible to take advantage of this functionality in varying environments. The following tutorial outlines an easy way for developers to understand how to rename a Git branch, an essential skill for taking full advantage of all that Git offers.
How to Rename Local Branch
First, you will learn how to rename a local branch using the git branch command in the terminal.
Start by switching to the local branch you want to rename.
git checkout <old_name>
Now rename the local branch you just switched to.
git branch -m new-branch-name
You can rename a different branch similarly with the following command:
git branch -m old-branch-name new-branch-name
For both examples, the -m flag stands for “move” and tells Git to rename the branch.
Alternatively, you can use the git branch command with the -M flag, which is the same as -m but also moves the branch HEAD to the new branch. This can be useful if you have already checked out the branch that you want to rename. For example:
git branch -M new-branch-name
This will rename the current branch and move the HEAD pointer to the new branch.
Lastly, verify the renaming was successful.
git branch -a
How to Rename a Remote Git Branch
Next, you will learn to rename a remote Git branch. You must delete the old branch and create a new one with the desired name. Here is an example of how you can do this using the terminal:
- Delete the old remote branch:
git push origin --delete old-branch-name
- Create a new branch with the desired name and push it to the remote:
git push origin new-branch-name
This will delete the old-branch-name branch on the remote and create a new branch called new-branch-name that tracks the local branch with the same name.
Alternatively, you can use the git push command with the -u flag, which stands for “upstream.” This flag sets the upstream branch for the new branch so that you can push and pull changes to and from the remote branch.
For example:
git push -u origin new-branch-name
This will create the new-branch-name branch on the remote and set it as the upstream branch for the local new-branch-name branch.
Conclusion
Git branches are mighty and offer a lot of flexibility to developers. Renaming local Git branches is a quick and easy process that can be done with a single command. However, you can’t directly rename a remote branch; you first need to push the renamed local branch and then delete the branch with the old name.