How to locally delete all remotely merged git branches

If you are like me and have a bad habit of not deleting your local branches as you merge them and delete them remotely, this one is for you.

A two commands solution

First command to fetch but as well prune any branches that no longer exist on the remote branch.

git fetch -p

-p is short for --prune.

Now that we have a clean slate we can perform an efficient deletion with the second command:

git branch -vv | grep ': gone]'|  grep -v "\*" | awk '{ print $1; }' | xargs git branch -D

Here is it decomposed:

git branch -vv

Which lists your local branches and including "gone" if it is not present anymore remotely. -vv means very verbose.

grep ': gone]'

Which filters all lines including : gone].

grep -v "\*"

Which ignores the currently checked out branch.

awk '{print $1}'

Which grabs the first column in the output, being the branch name.

xargs git branch -D

Which runs git branch -D for the names of the filtered branches.

Et voilĂ !

If for some reasons you want to exclude some branches that would show up in the filtered list, amend the grep -v "\*" command to something like egrep -v "(^\*|branch-to-keep1|branch-to-keep2)".

Reference

Remove branches not on remote, on Stack Overflow.