How To Delete a Local and Remote Git Branch
3 min read
Branches are part of the everyday development process and one of the most powerful features in Git. Once a branch is merged, it serves no purpose except for historical research. It is common and recommended practice to delete the branch after a successful merge.
This guide covers how to delete local and remote Git branches.
Delete a Local Git Branch
To delete a local Git branch use the
git branch command with the
git branch -d branch_name
Deleted branch branch_name (was 17d9aa0).
If you try to delete a branch which contains changes that are not merged in yet, you'll receive the following error message:
error: The branch 'branch_name' is not fully merged. If you are sure you want to delete it, run 'git branch -D branch_name'.
As the message above says, you can force the deletion by using the
-D option which is a shortcut for
git branch -D branch_name
Please note, if you delete an unmerged branch, you will lose all the changes on that branch.
git branch --no-mergedcommand.
If you try to remove the current branch, you'll get the following message:
error: Cannot delete branch 'branch_name' checked out at '/path/to/repository'
You can't delete the branch you're currently on. First, switch to another branch and then delete the
git checkout master git branch -d branch_name
Delete a Remote Git Branch
In Git, local and remote branches are separate objects. Deleting a local branch doesn't remove the remote branch.
To delete a remote branch, use the
git push command with the
git push remote_name --delete branch_name
remote_name is usually
git push origin --delete branch_name
... - [deleted] branch_name
There is also an alternative command to delete a remote branch, that is, at least for me harder to remember:
git push origin remote_name :branch_name
If you are working on a project with a group of people and try to delete a remote branch that is already removed by someone else, you will receive the following error message:
error: unable to push to unqualified destination: branch_name 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 'email@example.com:/my_repo'
In situations like this, you'll need to synchronize your branch list with:
git fetch -p
-p option tells Git to remove any remote-tracking references that no longer exist on the remote repository before fetching.
In this tutorial, you have learned how to delete local and remote Git branches. Branches are basically a reference to a snapshot of your changes and have a short life cycle. Once the branch is merged into the master (or another main branch), it is no longer needed and should be removed.
If you hit a problem or have feedback, leave a comment below.