Deleting a Git branch is usually straightforward. In this article, you’ll learn how to delete a Git branch both locally and remotely.
TL;DR version
// delete branch locally
git branch -d localBranchName
// delete branch remotely
git push origin --delete remoteBranchName
When to Delete branches
Git repositories commonly have multiple branches, which are an excellent way to work on different features or fixes while keeping the new code separate from the main codebase.
Repositories typically have a main branch for the primary codebase, while developers create additional branches to work on specific features.
After completing work on a feature, it’s generally recommended to delete the branch.
Deleting a branch LOCALLY
Git prevents you from deleting the branch you are currently on, so you need to switch to a different branch before deleting. For example: git checkout main
.
To delete a branch, use the command: git branch -d <branch>
.
For example: git branch -d fix/authentication
.
The -d
option deletes the branch only if it has already been pushed and merged with the remote branch. If you want to force delete the branch, even if it hasn’t been pushed or merged, use the -D
option instead.
The branch has now been deleted locally.
Deleting a branch REMOTELY
To delete a branch remotely, use the following command: git push <remote> --delete <branch>
.
For instance: git push origin --delete fix/authentication
.
The branch has now been deleted remotely.
Alternatively, you can use this shorter command to delete a branch remotely: git push <remote> :<branch>
.
For example: git push origin :fix/authentication
.
If you encounter the error below, it could mean that someone else has already deleted the branch.
error: unable to push to 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 synchronizing your branch list with the following command:
git fetch -p
The -p
flag stands for “prune.” After fetching, branches that no longer exist on the remote will be removed.
If you found this tutorial helpful, our nonprofit offers over 11,000 straightforward tutorials like this one, all for free. Feel free to share with your friends! 😉