Introduction
🧑💻 New to Git or LabEx? We recommend starting with the Quick Start with Git course.
In Git, a branch is a lightweight movable pointer to a commit. Renaming a branch is a common task in Git. However, renaming a branch both locally and on the remote can be a bit tricky. In this lab, you will learn how to rename a remote branch in Git.
Rename Remote Branch
To complete this lab, you will use the Git repository git-playground from your GitHub account, which comes from a fork of https://github.com/labex-labs/git-playground.git. Please uncheck "Copy master branch only" when forking.
You have a Git repository named https://github.com/your-username/git-playground. You have created a branch named feature-branch and pushed it to the remote. Now you want to rename the branch to new-feature-1 both locally and on the remote.
- Clone the repository, navigate to the directory and configure the identity:
git clone https://github.com/your-username/git-playground.git cd git-playground git config --global user.name "your-username" git config --global user.email "your-email" - Switch to the named
feature-branchbranch:git checkout feature-branch - Rename the branch both locally and on the remote:
git branch -m feature-branch new-feature-1 git push origin --delete feature-branch git push -u origin new-feature-1 - Verify that the branch has been renamed:
git branch -a
This is the result of running git branch -a:
* master
new-feature-1
remotes/origin/HEAD - > origin/master
remotes/origin/master
remotes/origin/new-feature-1
Summary
Renaming a remote branch in Git involves renaming the branch both locally and on the remote. You can use the git branch -m <old-name> <new-name> command to rename the local branch and the git push origin --delete <old-name> and git push origin -u <new-name> commands to delete the old remote branch and set the new remote branch, respectively.