In 2017, WikiLeaks released Vault7, a massive collection of CIA hacking tools and internal docs.
Tucked among the exploits was a simple page of developer notes with
git tips. Most of it was standard, amending commits, stashing
changes, using bisect, but one tip stuck with me and has lived in my ~/.zshrc ever since.
#
The problem
Over time, a local git repo fills up with stale branches. Every
feature, fix, and experiment you’ve ever merged just sits there,
doing nothing. Running git branch starts to feel like wandering
through a graveyard.
You can list merged branches with:
git branch --merged
But deleting them one by one is tedious. The CIA’s dev team has a
cleaner solution.
How does git know what was merged?
Git doesn’t track “merge events.” It tracks commit history.
Every commit points to its parent(s), forming a graph. When you
run git branch --merged, Git simply checks
whether the tip commit of a branch is already contained in the
current branch’s history (i.e., it’s an ancestor of HEAD).
If it is, Git considers the branch merged, even if you used a
fast-forward merge and no merge commit was created.
#
The original command
git branch --merged | grep -v "\*\|master" | xargs -n 1 git branch -d
git branch --mergedLists all local branches that have already been merged into the
current branch grep -v "\*\|master"
Filters out the current branch (*) and master xargs -n 1 git branch -dDeletes each remaining branch one at a time, safely (lowercase -d
won’t touch unmerged branches)
#
The updated command
Since most projects now use main instead of master, you can update
the command and exclude any other branches you frequently use:
git branch --merged origin/main | grep -vE "^\s*(\*|main$|develop$)" | xargs -n 1 git branch -d
Notice that we are using --merged origin/main
to check what was merged into origin/main,
rather than whatever branch you currently have checked out.
Tip
.... | xargs -n 1 echo git branch -d
This shows what would be deleted before actually deleting.
Small thing, but one of those commands that quietly saves a few
minutes every week and keeps me organised.