Remove git local branches that do not exist on remote anymore

I use Git for my professional development, and we create branches like crazy (one branch per feature and we do a lot of features in my company) so maintaining your local git repository sometimes gets a little complicated.

I needed a script that simply deletes my local branches that do not exists in the remote repository.

Sounds easy right?

Well, I'm in Windows environment so that sets the challenge to a new level. So I came with this little one line script

git checkout master; git fetch --all -p; git branch -vv | where { $_ -notmatch "\[origin\/" } | % { $_ } | sls -pattern "\S*\/[\S\-]*" | % { $_.Matches } | % { $_.Value } | select { "git branch -d $_" } | invoke-expression

  • First of all, checkout master.
  • Then fetch everything from the remote the repository and remove any remote-tracking references that no longer exist on the remote.
  • After that get the list of branches that do not contain a reference to "origin"
  • Select only the branch name in my case it's always something like feature/my-feature
  • Then simply delete the local branch

Note: Since it is using -d it will not delete branches that have not been fully merged.

I got the idea from StackOverflow although this post is for people that have grep or unix based sistems.

BTW I use the new git for windows

Enjoy it!