Delete a Local and or Remote Git Branch

When working with Git we often need to delete a branch locally as well as remotely. Let’s look at how we can do that:

Delete a local git branch

git branch -d branch_name

This command will delete the local git branch named branch_name. The -d flag is shorthand for for delete, which can also be written out in full as --delete.

Sometimes this command might fail even if the branch exists. This may be because it's in a conflicting push or merge status. Then, we have to use a little bit of force:

git branch -D branch_name

which is shorthand for

git branch --delete --force branch_name

Delete a remote git branch

Git version 1.7.0 or newer

git push remote_name -d branch_name

Git versions earlier than 1.7.0

git push remote_name : branch_name

remote_name is usually origin

git push origin -d branch_name

This command will delete the remote branch named branch_name

Special Use Cases

Deleting obsolete local branches

There might be scenarios where some remote branches were deleted using the web interface or by another developer, but the local branches still exist in your system and you want to delete those branches. This is where pruning comes in.

git fetch origin -p

-p is an alias for --prune

git fetch origin --prune

Deleting all branches except the master and the currently checked out branch

Sometimes you just want to keep the master branch and currently checked out branch on your local computer to reduce the clutter. This is a handy command for that:

git branch | grep -v "master" | grep -v ^* | xargs git branch -D

Note: This will only work in UNIX based system like macOS or Linux distribution (Ubuntu, Linux Mint, etc.)

How does it work?

First, we list out all the branches in the repo using git branch. It will output something like this:

  master
  develop
  patch-01
* bug_fix

Then, we pipe that output using the grep command with the -v flag (shorthand for --invert-match where the selected lines are those not matching any of the specified patters) we select all the branch_names except master and the current branch which starts with and asterisk *.

Finally, using xargs we execute git branch -D with each of the selected branch names. If the master branch is the currently checked out branch, it will delete all other branches except it.

Be careful while running this, notice the -D flag. It will force delete the selected local branches.