Working with branches in git can be confusing. One of the most commonly occurring causes of confusion for new git users is figuring out exactly how to delete both local and remote git branches. Good thing is, it is much easier to do than it sounds!
Related: How To Rename A Git Branch
How To Delete A Local Git Branch
The first thing you need to do if you want to delete a local branch is to check out to a different branch (one that you do not wish to delete). Git does now allow users to delete the branch that they are currently on. For example, you could checkout to your master branch by using the following command:
git checkout master.
Once you're on a different branch, you can use one either –
$ git branch -d <branch_name> $ git branch -D <branch_name>
-d flag is a shorthand version for
--delete. This command will only delete the branch if it has been merged and pushed to the remote origin.
On the other hand, the
-D option is shorthand for
--delete --force. This force deletes the branch irrespective of whether it has been merged or not.
How To Delete A Remote Git Branch
If you have already pushed your git branch to remote servers, you will have to follow a different method to remove and permanently delete it from the cloud.
$ git push <remote> --delete <branch_name> or $ git push <remote> :<branch_name>
Here, <remote> is the name of your remote repository. In most cases, this tends to be
For example, if you're deleting a remote branch named
fix/ui-nits on the remote
origin, your command would be:
$ git push origin --delete fix/ui-nits or $ git push origin :fix/ui-nits
Things To Keep In Mind When Deleting Branches
Depending on the version of git you are using, you might have remote-tracking branches in addition to your local and remote branches. When deleting a branch both locally and remotely, it might be a good idea to use the following command on all other computers that might be working on the same repository and therefore might contain obsolete tracking data.
$ git fetch --all --prune
git remote prune and
git fetch —prune erase references to branches that do not exist on the remote.
git fetch --all —prune connects to the remote and fetches the most recent remote state before pruning, thus combining two commands into one.
Some other useful commands when working with branches are listed below. These will help you verify if your branches still exist, either locally or remotely.
git branchto view all local branches
git branch -rto view your remote branches
git branch -ato view all local and remote branches