Git-Mastery: Lessons

T8L3. Deleting Branches from a Remote


Often, you'll need to delete a branch in a remote repo after it has served its purpose.

This lesson covers that part.

To delete a branch in a remote repository, you simply tell Git to remove the reference to that branch from the remote. This does not delete the branch from your local repository — it only removes it from the remote, so others won’t see it anymore. This is useful for cleaning up clutter in the remote repo e.g., delete old or merged branches that are no longer needed on the remote.

HANDS-ON: Delete (and restore) branches in a remote

Preparation

Option 1: Create a fresh sandbox using the Git-Mastery app

  • Navigate inside the gitmastery-exercises folder.
  • Run gitmastery download hp-remote-branch-delete command.

The sandbox will be set up inside the gitmastery-exercises/hp-remote-branch-delete folder.


Option 2: Manually set up a sandbox

Fork the samplerepo-books to your GitHub account as gitmastery-samplerepo-books. When doing so, un-tick the Copy the main branch only option.
After forking, go to the fork and ensure all three branches are in there.

Clone the fork to your computer.


1 Create a local copy of the fantasy branch in your clone.

Follow instructions in Lesson T8L2. Pulling Branches from a Remote.

2 Delete the remote branch fantasy.

 CLI

You can use the git push <remote> --delete <branch> command to delete a branch in a remote. This is like pushing changes in a branch to a remote, except we request the branch to be deleted instead, by adding the --delete switch.

git push origin --delete fantasy
Sourcetree

Locate the remote branch under REMOTESorigin, right-click on the branch name, and choose Delete...:

3 Verify that the branch was deleted from the remote, by going to the fork on GitHub and checking the branches page https://github.com/{YOUR_USERNAME}/gitmastery-samplerepo-books/branches
e.g., (if your username is ) https://github.com/[[username: JohnDoe]]/gitmastery-samplerepo-books/branches.

Also verify that the local copy has not been deleted.

4 Restore the remote branch from the local copy.

Push the local branch to the remote, while enabling the tracking option (as if pushing the branch to the remote for the first time), as covered in Lesson T8L1. Pushing Branches to a Remote.

In the above steps, we first created a local copy of the branch before deleting it in the remote repo. Doing so is optional. You can delete a remote branch without ever checking it out locally — you just need to know its name on the remote. Deleting the remote branch directly without creating a local copy is recommended if you simply want to clean up a remote branch you no longer need.

done!

EXERCISE: glossary-branch-delete