Delete multiple git branches at once
April 19, 2021 ‐ 2 min read
Cleaning up your local branches is one of my, somewhat boring, recurring tasks. Especially for projects with multiple developers(and running
git fetch often) my list of local branches gets quite large.
To remove a git branch you use the
git branch -D <branch_names> command. You can pass multiple branch names to this command, separated by a space. Unfortunately
git branch -D doesn't allow globbing patterns, unlike the
rm command for example.
The tab completion in Zsh already goes a long way in making deleting multiple branches faster. But we can do better. With
git branch --format "%(refname:short)" | grep "<pattern>" | xargs git branch -D we can use the
grep command to specify a pattern for the branch names.
Look at the following for example, which removes git branches with names starting with
$ git branch --format "%(refname:short)" | grep "^fix/*" | xargs git branch -D
If you rather have some security first you can run the following command first, which displays the list of branches without deleting them.
$ git branch --format "%(refname:short)" | grep "^fix/*"
Removing local branch with prune
Another option would be to use
prune you prune away the branches that don't exist on the remote anymore. So the local branches that are not present on the remote repository anymore will be deleted.
$ git remote prune origin