How to delete merged Git branches

Overview

This answer explains how to delete Git branches that are merged.

Here, we assume that master, main, and develop are the important branches. Other branches may be the feature branches, which may or may not already be merged.

The git branch command

The git branch command is used to interact with the branches of Git. With this command, we can create, list, or delete branches.

The basic syntax of the git branch command is as follows:

git branch <OPTIONS>

The options relevant to this Answer are as follows:

  • --merged: This lists the branches that were merged to the tip of the current branch.
  • -d: This is used to delete the specified branch.
  • -r/--remotes: This is used to list the remote-tracking branches.

Deleting local branches

There are two steps to delete Git local branches that are merged, as follows:

  1. List the branches that are merged.
  2. Delete the branches.

The following command is used to list the local branches that are merged. Here, master, main, and develop are excluded.

git branch -r --merged| egrep -v "(^\*|master|main|develop)"

To delete the branches locally, we use:

git branch -d branch-name

The above two commands can be combined into a single command as follows:

git branch -r --merged | egrep -v "(^\*|master|main|develop)" | xargs -n 1 git branch -d

Deleting remote branches

A branch can be deleted from a remote using the following command:

git push --delete origin branchname

In sum, to delete remote branches that are merged, we can use the following command.

git branch -r --merged | egrep -v "(^\*|master|main|develop)" | xargs -n 1 git push --delete origin

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved