Bulk delete git branches

A pile of logs

As a software engineer using git, and especially those adopting the gitflow workflow, you will often get to a point where the number of feature/* and bugfix/* branches grows unwieldly. To keep your repository clean and free of cruft it's a good idea to delete these branches.

Begin by listing all local branches by running the following command from the root of your repositiory:

git branch --list

If you look closely you'll notice develop and master branches included in the output. You almost certainly won't want to delete those branches so we need a way to filter the output before deleting.

Filter branch list

Luckily git has a simple way to filter the output.

git branch --list 'bugfix*'

This filters the output to only include branches begining with 'bugfix'.

Bulk delete using xargs

Finally, we pipe the output into xargs which executes the delete branch command git branch -d.

git branch --list 'bugfix*' | xargs -I % git branch -d %

You may be wondering what the -I % is. This tells xargs to execute our command once for each line of input assigning each line to placeholder %. It's worth noting % is arbitrary and could be another character, _ for example.

Hi, I'm Will

I'm a lead software engineer with over 13 years experience from Melbourne Australia. Got a project you'd like to discuss? Reach me below.