If you follow a typical git workflow you will probably have been developing each feature, or fixing each bug, on it’s own branch, and then merging each branch into a central development branch in the remote repo. In this kind of scenario at the end of a project you may have many local branches that are left over from this process. And now you need to delete both the local branch and the remote branches (as long as they’ve been merged!). In this post I’ll cover how to delete a branch in git – more specifically how to delete a local git branch, and how to delete a remote git branch.
How to delete a local git branch
Before you delete a local branch you need to be very sure that you have the name spelled EXACTLY right. It’s useful to see all your local git branches using the git branch command, so you can see a list of them and make a note of the name of the branch you want to delete.
Even more useful though is this command:
git branch --merged
…. which will show all the branches that have been merged into the current one.
Let’s say that we want to delete the branch that’s called feature-12 from the list shown in the image above. You can see that main is highlighted in green, and that it has an asterisk next to it – that’s telling us that we are currently on the branch called main. We can now run the command to delete the local branch feature-12 as follows:
git branch -d feature-12
It’s the -d flag that tells git to delete the local branch specified. So to delete a branch called temp-develop, for instance, you would type:
git branch - d temp-develop
And as long as that has been deleted ok you’ll see a simple message saying ‘Deleted branch feature-12 …‘ confirming it worked fine.
When can’t you delete a branch
- You can’t delete a branch that you’re already on – so change branches and then delete it.
- You can’t delete a branch if it contains work that hasn’t been checked in – so you should commit and push the changes, or stash them, or discard them.
Force delete a branch with work that isn’t checked in
You can use the -D flag to force deleting a branch even with work that isn’t checked in.
How to delete a remote git branch
You can delete a remote git branch from the command line by using this command:
git push origin --delete branchNameHere
So if we were deleting a remote branch called bugfix-CA619 we would type:
git push origin --delete bugfix-CA619
So now you know how to delete both local and remote git branches, and you know how to force delete, although I would very much recommend not doing this as you could lose unsaved changes!