DEV Community

Raj Maharjan
Raj Maharjan

Posted on • Updated on

Delete merged branches using one command

Here is a command that you can use to delete all the branches that have been merged to master branch from both local and remote using just one command. Instead of deleting branch one by one, I use below commands to delete all the branches that have been merged.

Delete local merged branches:
git branch --merged master | egrep -v "(^\*|master|dev)" | xargs -n 1 git branch -d
Enter fullscreen mode Exit fullscreen mode
Delete remote merged branches:
git branch -r --merged master | egrep -v "(^\*|master|dev)" | cut -d/ -f2- | xargs -n 1 git push --delete origin
Enter fullscreen mode Exit fullscreen mode

You can change branch name from master to any other branch name that you refer to as your main branch.

Also you can use it as alias by adding it in .bashrc file.
alias gclb='git branch --merged master | egrep -v "(^\*|master|dev)" | xargs -n 1 git branch -d'
alias gcrb='git branch -r --merged master | egrep -v "(^\*|master|dev)" | cut -d/ -f2- | xargs -n 1 git push --delete origin'

Enter fullscreen mode Exit fullscreen mode

It has been a lot easier for me to use it this way. If you do it differently or have better way please comment below.

Top comments (4)

Collapse
 
andreipavel0 profile image
Andrei Pavel • Edited

Or as I prefer it, part of .gitconfig:

[alias]
  delete-merged-local-branches = ! git branch --merged master | grep -Ev '(^\\*|master)' | xargs -n 1 git branch -d
  delete-merged-remote-branches = ! git branch -r --merged master | grep -Ev '(^\\*|master)' | cut -d '/' -f2- | xargs -n 1 git push --delete origin
Enter fullscreen mode Exit fullscreen mode

Then:

$ git delete-merged-local-branches
$ git delete-merged-remote-branches
Enter fullscreen mode Exit fullscreen mode

Thanks for sharing!

Collapse
 
deniscloudgeek profile image
Denis Trofimov

Your "cut" step is not working for a branch name "feature/HCB-446-sonar-workflow".
But "git branch --merged | egrep -v "(^*|master|main|dev)" | xargs git branch -d" works.

Collapse
 
rajmaharjan profile image
Raj Maharjan

Thanks for pointing out @deniscloudgeek, indeed the cut command is not needed when deleting local branches.
However, it is needed when deleting remote branches - removes origin/ from branch name.
Updated!

Collapse
 
sinepel profile image
Constantin Boulanger

Hi! Great tips, thanks for sharing! :)