It is a good practice that we delete the branches once they are merged.
Branches are just a pointer to a sepecific commit, once they are merged the commit is already there in the target branch, so there is no point to have merged branches cluttered in our project.
One other advantage of deleting merged branches is that we will be able see the current development, whenever you do git branch
How to see merged branches?
git branch --merged
How to delete a branch?
git branch -d branch_name
Note:
• git will warn you if the branch being deleted is not fully merged. However, if you want to delete partially or non-merged branches you can use,
git branch -D branch_name
• All hyperlinks URLs references of your DELETED branches, will be BROKEN.
For exmaple: if you delete branch_feature_x
branch from your repo
The corresponding hyperlink URL of this branch will be broken
https://github.com/username/project/tree/branch_feature_x
How to delete multiple merged branches with a single command?
xargs: allows you to pass outputs as input to another command.
example: ls | grep filename| xargs rm
Above command will feed output from ls
to grep
which will find all files having word filename
. grep
further will pass them to xargs, and xargs will feed them to rm
So, all the files having word filename
in their name will be deleted.
We can apply the same concept to git branch --merged
output.
git branch --merged| egrep -v "(^\*|master|dev)"| xargs git branch -d
Above command will delete all the branches excluding those matches with master or dev
.
If you want to exclude other specific branch you can simply pass that in the arguments,
git branch --merged | egrep -v "(^\*|master|main|dev|feature_x)" | xargs git branch -d
Note: egrep uses Extended Regular Expression and in this you can use commands like this egrep 'a|b'