How to Delete Local and Remote Git Branches

Overview

Depending on your branch strategy, once finished with a branch there is usually little need for keeping it around. This tutorial will show you how to remove old, unused branches from your local Git repository.

When a gitflow branching strategy is used a feature branch is created for every feature, as well as bugfix branches for bugfixes, etc. These branches typically have a very short lifespan, especially in environments practicing Agile or XP programming.

Keeping your repository organized and clean ensures other developers are able to navigate your code repository. Littering your repository with out-dated branches can make it difficult finding for others following your project, or even on-boarding other developers.

Deleting Local Git Branches

To delete a local Git branch use the -d or –delete flag with the branch command. Also, it must not be an active branch. If it is you will need to check out a different branch first.

For example, to delete a local branch named feature/my-new-feature, we would use run the following command.

git branch -d feature/my-new-feature

or, using the –delete flag

git branch --delete feature/my-new-feature

Both delete flags do the same operation, so there there is no difference. Using the –delete flag rather than the -d flag makes sense when you want a clear understanding of what operation is being done.

Git Delete Branch If Not Merged

In order to delete a local branch that has not been merged into your main branch, you use the -D flag instead of -d or --delete.

git branch -D feature/my-new-feature

Forcefully Git Delete Branch

To force delete Git branches that are in your local repository you use to. -f or --force flags.

git branch -d -f feature/my-new-feature

Deleting Remote Branches

In a team project with multiple developers working on the same feature branch, there’s a very good possibility the feature branch has been pushed to the remote repository.

The -d and –delete flags will only delete the local copy of a branch. In order for the remote copy to be deleted we will use a different method. Will still use the –delete flag, but we use it with the push command and we target the repo name with the branch name.

git push --delete origin feature/my-new-feature

Force Git Delete Remote Branch

To forcefully delete a remote branch, use the -f or --force flag.

git push --delete -f origin feature/my-new-feature

Deleting Local and Remote Git Branches

If you are deleting one copy of the branch you may need to delete the other as well. The following sequence should be used to delete both local and remote branches.

git push --delete origin feature/my-new-feature
git branch --delete feature/my-new-feature