Here's a zsh alias that uses gum to interactively list and delete local Git branches that don't have a remote tracking branch:
alias clean-local-branches='for branch in $(git for-each-ref --format='"'"'%(refname:short) %(upstream)'"'"' refs/heads | awk '"'"'$2 == "" {print $1}'"'"'); do gum confirm "Delete local branch '\''$branch'\''? (no remote tracking)" --affirmative="Delete" --negative="Skip" && git branch -D "$branch"; done'
How it works:
- Lists all local branches without upstream (remote tracking) branches using
git for-each-ref
- For each such branch, uses
gum confirm to ask whether to delete it
- If you select "Delete", it runs
git branch -D on that branch
- If you select "Skip", it moves to the next branch
Requirements:
Alternative (multi-line version for readability):
If you prefer a more readable multi-line version (which you could add to your .zshrc):
clean-local-branches() {
for branch in $(git for-each-ref --format='%(refname:short) %(upstream)' refs/heads | awk '$2 == "" {print $1}'); do
if gum confirm "Delete local branch '$branch'? (no remote tracking)" --affirmative="Delete" --negative="Skip"; then
git branch -D "$branch"
fi
done
}
This version works the same way but is easier to read and modify. You would use it the same way by just typing clean-local-branches in your terminal.