Cleanup Local Git Branches

Here's how to quickly delete many local git branches.

Over time, as we work, there are many git branches that pile up on our local machine. To see them:

git branch

Delete One Branch at a Time

To delete one branch at a time, we name the branch and pass a -D option:

git branch -D my-branch

Delete Many Branches at a Time

To delete more than one branch, we need to create a list of branches. Most often, the list I want is everything but the main/trunk branch. This list is the list of all branches with the master branch filtered out. To do this, list all branches then pipe through an inverse grep (-v):

git branch | rg -v master

Finally, pipe this list (with branches on separate lines) into a single line git branch -D command with xargs. All together:

git branch | rg -v master | xargs git branch -D

What other methods do you like to use?