Renaming a Local GitHub branch and applying the change to its corresponding Remote branch


So, this is a ‘Tutorialeto’ to help you rename your GitHub branches when suddenly your Program Manager asks you to change the names as per her standards(I know you hate that 😛 ).

git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote

The following commands will help you accomplish the same. Enjoy!

Branching in Git

Nope, there’s no harm in running and playing around in Git. Branches? Nope, not an issue! They are easy to master. All you need to keep in mind while thinking of Branching in Git are :

  • HEAD pointer
  • Commit history ( A linked chain of commits )
  • A few commands
  • To understand branching we should first understand how Git stores data. It is stored in the form of Snap shots that is actually a chain of commits from the first commit to the most recent commit.

    So, think of a commit as a trigger. As we make a commit the following events occur :
  • A new commit object is created
  • Previous commit object points to the new commit object
  • HEAD pointer points to the branch with the new commit object 

    What is HEAD ? It is just a special pointer in Git that’s used to point to the most current branch. So, if you made a commit , say, in branch master,HEAD points to branch master. But, if you perform the following command git checkout -b testing Git will create a new branch testing and will move HEAD to point to the new branch which basically points to the latest commit object of branch A. Similar stuff happens to an existing branch too. Now, if you commit from testing, HEAD will still point to this branch but this branch will move forward in the project. This means that from the previous commit object which was being pointed to by both branch master and testing points to the new commit object which is in branch testing now and is being pointed to by HEAD while branch master still points to the previous commit. Apparently, it means that this doesn’t in any way affect master. But, now if we run the commands :

  • git checkout master
  • git add changed_file
  • git commit -m "Just committed"
  • a new diverging commit object created. This means that the first commit object now points to two different commit objects belonging to two different branches master and testing where HEAD still points to the most recent branch, in this case master. The image below illustrates a similar situation for two branches master and testing situation.

    Now I am quite sure that you are more comfortable with Git Branching than you have been 10 minutes earlier. To view the current status of the branch pointers and HEAD just type the following command :

  • git log --oneline --decorate