Quick Git - Delete local branches without remote

post-thumb

An orphaned branch is a local branch whose remote was deleted. This happens a lot for example when squash merging feature branches into develop and automatically deleting them from remote after the PR completes. Because I tend to forget to delete them also locally, this often leaves me with a lot of old feature branches I from time to time want to dispose. Somehow, there is no built-in git command for that – so I wrote my own!

PowerShell variant

git fetch -p; git branch -vv | sls 'gone' | ? { -not $_.Line.startsWith('*') }  | % { $_.Line.trim().split(' ')[0] } | % { git branch -D $_ }

Linux Shell variant:

git fetch -p && git branch -vv | grep gone | cut -d' ' -f 3 | grep . | xargs git branch -D

These will git fetch all current branches from remote with the -p switch telling git to prune the branches not present there anymore, marking them as gone. Next, those goners will be scraped from the output of git branch and deleted locally each using git branch -D.

Bonus

Copying the one-liners all the time quickly gets tedious – make an alias for them!

Under Windows, you can add the following to your PowerShell Profile (read more about PowerShell Profiles here)

function Remove-GitOrphanedBranches {
    git fetch -p
    git branch -vv | sls 'gone' | ? { -not $_.Line.startsWith('*') } | % { $_.Line.trim().split(' ')[0] } | % { git branch -D $_ }
}

Set-Alias git-rm-orphanedbranches Remove-GitOrphanedBranches

Under Linux, just add the following to your ~/.bash_profile (or wherever you export your aliases)

alias git-rm-orphanedbranches="git fetch -p && git branch -vv | grep gone | cut -d' ' -f 3 | grep . | xargs git branch -D"

Then, you can just leverage git-rm-orphanedbranches at any time to clean up after yourself.

Der Objektkultur-Newsletter

Mit unserem Newsletter informieren wir Sie stets über die neuesten Blogbeiträge,
Webcasts und weiteren spannende Themen rund um die Digitalisierung.

Newsletter abonnieren