When working with Git, you may want to rename a local branch. This can be useful when you want to give the branch a more descriptive name or when you want to avoid naming conflicts. In this tutorial, we will walk through the steps for renaming a local Git branch.
To rename the current branch, use the following command:
git branch -m <newname>
For example, if you want to rename the current branch to "new_branch", use the following command:
git branch -m new_branch
To rename a branch while pointed to any branch, use the following command:
git branch -m <oldname> <newname>
For example, if you want to rename a branch called "old_branch" to "new_branch", use the following command:
git branch -m old_branch new_branch
Once you have renamed the local branch, you will need to push the changes to the remote repository and reset the upstream branch. To push the local branch and reset the upstream branch, use the following command:
git push origin -u <newname>
For example, if you renamed the local branch to "new_branch", use the following command:
git push origin -u new_branch
If you want to delete the old remote branch after renaming the local branch, use the following command:
git push origin --delete <oldname>
For example, if you renamed the local branch from "old_branch" to "new_branch", use the following command:
git push origin --delete old_branch
If you want to create a Git rename alias to simplify the renaming process, use the following command:
git config --global alias.rename 'branch -m'
Once you have created the alias, you can use the following command to rename a branch:
git rename <oldname> <newname>
If you are using a case-insensitive filesystem (such as Windows), you may need to use the "-M" option instead of the "-m" option when renaming a branch that only has capitalization changes in the name. Otherwise, Git may throw a "branch already exists" error. For example, if you want to rename a branch called "old_branch" to "New_Branch" on a case-insensitive filesystem, use the following command:
git branch -M New_Branch
In this tutorial, we covered the steps for renaming a local Git branch. To summarize:
git branch -m <newname>
" command.git push origin -u <newname>
" command.git push origin --delete <oldname>
" command (optional).git config --global alias.rename 'branch -m'
" command (optional).