A Time-Saving  Git Alias - "git sweep"

A Time-Saving Git Alias - "git sweep"

Delete all local branches linked to deleted remote branches with just one command!

I never remember the command for cleaning my remote branches so I decided to create an alias for them.

The alias

git sweep

This is a shortcut for the git fetch --prune command and a script that finds branches marked as gone then deletes all of them. There's more detail about the process here: https://www.erikschierboom.com/2020/02/17/cleaning-up-local-git-branches-deleted-on-a-remote/

Setting the alias

You can set them using the git config command or edit the git config file directly.

Here's the command to set the alias with the git config command:

git config --global alias.sweep "! git fetch -p && git for-each-ref --format '%(refname:short) %(upstream:track)' | awk '\$2 == \"[gone]\" {print \$1}' | xargs -r git branch -D"

Here's what the config file should look like with the alias added:

[alias]
sweep = ! "git fetch -p && git for-each-ref --format '%(refname:short) %(upstream:track)' | awk '$2 == \"[gone]\" {print $1}' | xargs -r git branch -D"

Special Thanks

Thank you Erik Schierboom for providing the solution. Hopefully, this gets added directly into Git one day. This alias is super useful for maintaining your repositories.