2019-04-30
|~2 min read
|293 words
To rename the name of a branch, there are four potential steps:
Checkout the existing branch (the one you want to rename):
% git checkout <old_name>
Rename the local branch by moving it:
% git branch -m <new_name>
If you’ve already pushed the <old_name>
branch to the remote repository delete the <old_name>
remote branch:
% git push origin --delete <old_name>
Finally push the <new_name>
local branch and reset the upstream branch:
% git push origin -u <new_name>
That’s it. At this point you have successfully renamed your local and remote Git branch.
-m
flagSimilar to the mv
command in Bash, the -m
flag is for moving. Since you’re on a branch, Git infers the branch that’s being moved, however, you can be explicit and consolidate steps 1 and 2:
git branch -m <oldbranch> <newbranch>
If you use bash or zsh and want to wrap this all up in a function, I did this with a function I call grb
which is in my .zshrc
:
function grb(){
# git rename branch
# this will rename the current branch and update the remote ref too
# if *no* remote existed, a new one will be created anyway.
CURRENT_BRANCH=$(git branch --show-current)
NEW_BRANCH_NAME=$1
REMOTE=$(git remote)
echo "Renaming branch from $CURRENT_BRANCH to $NEW_BRANCH_NAME"
git branch -m $NEW_BRANCH_NAME
echo "Deleting remote reference of $CURRENT_BRANCH"
git branch $REMOTE --delete $CURRENT_BRANCH
echo "Pushing a reference of $NEW_BRANCH_NAME to $REMOTE"
git push $REMOTE --set-upstream $NEW_BRANCH_NAME
echo "DONE"
}
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!