How to delete a branch in git

Whether you use GitFlow, GitHub Flow, or any other branch-based development strategy, you will automatically end up with a local Git repository full of branches you no longer need. That’s why it’s useful to know the command to delete Git branches locally and permanently so they don’t spoil your local development environment. In most cases, deleting a Git branch is easy. But in this article, you will learn how to delete a branch locally and remotely in GIT.

TLDR Version

// delete branch locally
git branch -d localBranchName
// delete branch remotely
git push origin --delete remoteBranchName

When To Delete Git Branches?

This is common for a Git repository to have multiple branches. They are an excellent method of working on various features and fixes while keeping the new code isolated from the main codebase.

Repositories frequently have a main branch for the main codebase, and developers build additional branches to work on various features. Once you’ve finished working on a feature, it’s generally recommended to delete the branch.

How To Delete a GIT Branch LOCALLY?

This will not allow you to delete the branch that you are presently on. So, you have to make sure the check out a branch that you are not deleting. For example, git checkout main.

If you want to delete a branch then: use git branch -d <branch>.

For Instance:- git branch -d fix/authentication

If the branch has already been pushed and merged with the remote branch, then the -d option will delete it. If you want to force the branch to be deleted even if it hasn’t been pushed or merged yet, then you can use -D.

Now Locally, the branch has been deleted.

Delete a GIT Branch REMOTELY?

Here is the command on how to remotely delete a branch, you just need to do this: git push <remote> –delete <branch>.

For instance: git push origin –delete fix/authentication

Finally, the Git branch is deleted remotely.

You can also use this shortcut command to remotely delete a branch: git push <remote>:<branch>

For Instance:- git push origin: fix/authentication

If you get an error like below, it means someone else has already deleted the Git branch.

error: unable to push to an unqualified destination: remoteBranchName The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to 'git@repository_name’

Try to synchronize your branch list using:

git fetch -p

The -p flag indicates that you want to “Prune”. After the fetch, branches that no longer exist on the remote will be deleted.

Scroll to Top