Software Engineering for Self-Directed Learners »

Tools → Git and GitHub →

Renaming Branches in a Remote


Occasionally, you might need to rename a branch in a remote repo.

This lesson covers that part.

You can't rename remote branches in place. Instead, you create a new branch with the desired name and delete the old one. This involves renaming your local branch to the new name, pushing it to the remote (which effectively creates a new remote branch), and then removing the old branch from the remote. This ensures the remote reflects the updated name while preserving the commit history and any work already done on the branch.

HANDS-ON: Rename branches in a remote

This hands-on practical can be done using the fork and the clone of the samplerepo-books that you created in Lesson: Deleting Branches from a Remote.

Rename the branch fantasy in the remote (i.e., your fork) to fantasy-books.

Here are the steps:

  1. Ensure you are in the master branch.
  2. Create a local copy of the remote-tracking branch origin/fantasy.
  3. Rename the local copy of the branch to fantasy-books.
  4. Push the renamed local branch to the remote, while setting up tracking for the branch as well.
  5. Delete the remote branch.
git switch master                     # ensure you are on the master branch
git switch -c fantasy origin/fantasy  # create a local copy, tracking the remote branch
git branch -m fantasy fantasy-books   # rename local branch
git push -u origin fantasy-books      # push the new branch to remote, and set it to track
git push origin --delete fantasy      # delete the old branch

You can run the git log --oneline --decorate --graph --all to check the revision graph after each step. The final outcome should be something like the below:

* 355915c (HEAD -> fantasy-books, origin/fantasy-books) Add fantasy.txt
| * 027b2b0 (origin/master, origin/HEAD, master) Merge branch textbooks
|/|
| * a6ebaec (origin/textbooks) Add textbooks.txt
|/
* d462638 Add horror.txt

Perform the above steps (each step was covered in a previous lesson).