The quick way
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
NB: if you’re not on master, this has the potential to delete the branch. Keep reading for the “better way”.
Make sure we keep master
You can ensure that master, or any other branch for that matter, doesn’t get removed by greping for more. In that case you would go:
git branch --merged | grep -v "\*" | grep -v "YOUR_BRANCH_TO_KEEP" | xargs -n 1 git branch -d
So if we wanted to keep master, develop and staging for instance, we would go:
git branch --merged | grep -v "\*" | grep -Ev "(\*|master|develop|staging)" | xargs -n 1 git branch -d
Make this an alias
Since it’s a bit long, you might want to add an alias to your .zshrc or .bashrc. Mine is called gbpurge (for git branches purge):
alias gbpurge="git branch --merged | grep -Ev "(\*|master|develop|staging)" | xargs -n 1 git branch -d"
Then reload your .bashrc or .zshrc:
. ~/.bashrc
or
. ~/.zshrc