Git Rename Branch Note
This week I did some research and worked on git rename branch on work. Just want to take a quick note to preserve my memory.
Change name for local branch
Method 1: Checkout to the branch you want to rename
git checkout <old branch name>
checkout to the branchgit branch -m <new branch name>
rename new name
Method 2: Without checkout to branch want to rename
git branch -m <old branch name> <new branch name>
rename old branch name to new name with 1 command
Don’t forget to update the remote branch name if you’ve pushed the local branch to remote before changing the local branch name!
Change name for remote branch
Method 1: Push new branch name to remote first and then delete remote old branch name
git push origin -u <new branch name>
(the same with git push — -set-upstream origin <new branch name>
if you prefer)
and then rungit push origin --delete <old branch name>
to remove remote old branch name
Method 2: Replace remote old branch name with new branch name, in 1 command
Most of the online resources indicate that it’s impossible to change remote old branch name with new branch name directly. However, I found one command to do it and the test result is successful. So I’ll still share the magical command with you guys.
git push origin <new branch name> :<old branch name>
Check and set correct upstream between local and remote branches
You can run git pull
to check if the local and remote branches are linked correctly. If not, just reset the upstream and you’re all set.
git branch —-set-upstream-to=origin/<new branch name>
Wish this post help whoever needs the information. Feedback and comments are welcome! 😺