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.
git branch
commandThe 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.There are two steps to delete Git local branches that are merged, as follows:
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
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