At the end of a project you may have many local branches that are left over from the process of managing feature branches. So now you need to know how to delete the local branches. In this post I’ll cover how to delete a local branch in git, and I’ll also explain how to list all your local branches so you can be sure you use the correct name before you delete anything!
How to list local branches
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.
How to remove a local git branch
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 (read more here about how to switch branches with git).
- 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.
So now you know how to list all of your local branches and delete them. You may also find this post useful as it explains how to delete your local git branches which no longer track a remote branch.