Renaming git branch Local and Remote

Ankit Wadhwana
TechVerito
Published in
2 min readApr 29, 2022

How often it has been that you created a new branch and accidentally spelled it wrong or you started working with a branch and later down the timeline there was a need to change the branch name?
I’m sure we all have run into such kinds of scenarios.

Modern code editors like IntelliJ IDEA and VS Code come with inbuilt functionality to do this. But if you’re not familiar with it Google might be the ultimate solution.

The steps to rename will be as follows:

git checkout <old_name>
git branch -m <new_name>
git push origin -u <new_name>
git push origin --delete <old_name>
  1. We start by switching to the branch we want to rename
    git checkout <branch_name>
  2. Rename the local branch by
    git branch -m <new_name>
    With this, we have renamed the local branch but in case the branch is already pushed to the remote the following steps are needed to delete it from the remote.
  3. Push the renamed branch <new_name> to the remote and reset the upstream branch
    git push origin -u <new_name>
  4. Finally, delete the old branch<old_name> remote
    git push origin --delete <old_name>

That’s all we need to do but wait what if we can automate this process?
Sound sweet! Let’s do it!

Now that we have a shell script to do this let’s make it executable by
Make sure to be in the directory where the script is located and at the command line type chmod u+x rename_git_branch.sh

With this, we can now run our script like ./rename_git_branch.sh
This is good but now the problem is we need to remember the path to this shell script whenever we want to run it. Seems like an overhead. But we can create an alias to run the command for us.

echo "alias <new name>='/home/<full path to script>/rename_git_branch.sh'" >> ~/.bashrc#example: echo "alias gitrename='~/scripts/rename_git_branch.sh'" >> ~/.bashrc

With this in the .bashrc the file we can now run the script directly by using gitrename in the terminal.

P.S. Don’t forget to run source ~/.bashrc after making changes to the .bashrcfile.

For ZSH users, this process is even simpler. It requires some changes in the shell script. Replace the lines in the shell script as follows:

Line no. 1 with #!/bin/zsh
Line no. 8 with function rename() {
and remove the function call from line no. 38

Now that we have modified the script we need to make sure that the zsh loads this scrip.
echo "source ~/scripts/rename_git_branch.sh" >> ~/.zshrc

To apply changes made to .zshrc: omz reload

Connect

Email: 24ankitw@gmail.com
Linkedin: https://www.linkedin.com/in/awadhwana/

--

--