How to delete a remote Git branch

It’s easy to delete a local Git branch. A simple git branch command with the -d flag and the name of the branch will more than suffice.

git branch -d feature-branch

But if that local Git branch was created through a pull from are remote repo like GitHub or BitBucket, how do you delete the remote branch as well? And for that matter, how do you delete the reference to the remote branch in your local Git repo?

Remote Git branch delete command

There are many ways to delete a remote Git branch that lives on GitHub or BitBucket. If you have administrative access to the GitHub or BitBucket landing pages for your repo, there are plenty simple, of point-and-click deletion options for unprotected branches.

Alternatively, you can issue either of the following Git commands to delete a remote branch:

  1. git push origin --delete <branch>
  2. git push origin -d <branch>

The only problem is, depending on which version of Git you are using, your local repo may still retain a remote reference that points to the remote branch you just deleted. This is known as Git’s remote tracking branch.

So a thorough branch removal strategy may requires the explicit deletion of this remote tracking branch as well.

Delete remote tracking branch in Git

You can delete a remote tracking with the following git branch command:

git branch --delete --remotes origin/branch-name

However, if the branch has already been deleted from the GitHub or BitBucket server, a simpler approach is to call the git fetch command with the prune option. The prune option removes any remote tracking branch in your local repository that points to a remote branch that has been deleted on the server.

git fetch origin --prune

With the local branch deleted, the remote tracking branch deleted, and all instances of the remote git branch deleted as well, the remote Git branch should be gone forever.

delete git remote local branch remove

These commands will delete both local and remote Git branches.

Steps to delete remote Git branches

In review, the steps to delete remote Git branches are:

  1. Issue the git push origin –delete branch-name command, or use the vendor’s online UI to perform a branch deletion
  2. After the remote branch is deleted, then delete the remote tracking branch with the git fetch origin –prune command
  3. Optionally delete the local branch with the git branch -d branch-name command

Remember, Git is a fully distributed system, and repositories may be cloned any number of times.

Most organizations use GitHub or BitBucket as a single source of truth, but there may be any number of clones of a given Git repo.

While the commands discussed here will delete branches from local and remote repos, there is always a chance that the branch still exists on a clone of the repository of which you are not aware.

App Architecture
Software Quality
Cloud Computing