DEV Community

Mehmet Seçkin
Mehmet Seçkin

Posted on • Originally published at on

Clean up git branches that do not exist on origin

Clean up git branches that do not exist on origin

After our team worked on a git repository for a while, we accumulated a lot of useless branches that are no longer being used. We’ve removed these branches regularly from the origin, but the local branches remained in everyone’s workstations like zombies.

It was time to do something.

That’s when we decided to combine the powers of git fetch --prune and shell scripting to forge a PowerShell function that will kill the zombie branches in our local repositories.

The script simply uses git fetch --all --prune to update all remote references (--all) and drop deleted ones (--prune).

After this, it filters out the local branches that do not exist on the origin by scraping the output of git branch -vv, and deletes the zombie local branches.

Here’s the whole thing:

Remove local git branches that are deleted from the origin.

Removes local git branches that are deleted from the origin using `git fetch --prune` and `git branch -[dD]`.

Switch to to force removal using `git branch -D` instead of `git branch -d`.

Removes merged non-existing branches.

Remove-DeletedGitBranches -Force
Removes all non-existing branches.

This cmdlet uses `git fetch --prune`, so it will delete references to non-existing branches in the process. Use with caution.
function Remove-DeletedGitBranches

    $null = (git fetch --all --prune);
    $branches = git branch -vv | Select-String -Pattern ": gone]" | ForEach-Object { $_.toString().Split(" ")[2] };
        $branches | ForEach-Object {git branch -D $_};
        $branches | ForEach-Object {git branch -d $_};        

Set-Alias -Name "rmdelbr" -Value Remove-DeletedGitBranches

Top comments (0)