Delete git branches no longer present in remote

Context #

I am cleaning up branches in a local repository that are no longer present in the remote origin repository. Since the number of branches is 20+, I didn't want to manually remove each of the dangling branches.

Implementation #

The implementation leverages the output of git branch -vv to show information about state of the remote-tracking branch, if any.

  1. Let's remove first any remote-tracking ref that no longer exist on the remote.
git fetch --prune
  1. Let's get the list of branches whose remote tracking branch is gone (removed in the previous step), select the branch name from the console output and force delete them.
git branch -vv |
Select-String gone |
ForEach-Object { $_.ToString().Trim() } |
ForEach-Object { ($_ -split "\s")[0] } |
ForEach-Object { git branch -D $_ }

Note #

For safety before running the full pipe command, I would suggest the following:

  1. Remove the ForEach-Object { git branch -D $_ } and verify that it lists the expected branches
  2. Then, replace the removal command with the non-force version ForEach-Object { git branch -d $_ }

It can also happen that this doesn't remove all the branches. There are instances where the local branch is missing the remote tracking information and thus, it will be skipped from the above pipe command. In that case, you will need to manually delete them.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.