How To Delete All Git Branches Except Master
Git
12/04/2021
If you wish to delete all Git branches except for one, run the command below. Replace "master"
if your main branch is named differently.
git branch | grep -v "master" | xargs git branch -D
Of course, make sure not to be on a branch that will be deleted, or else you will run into an error.
How it works
Let's quickly cover some Unix basics to properly understand the logic of this command.
|
, also known as the pipe symbol, serves to take the output of the previous command and feed it as an input to the next one. However, not every command like grep
will understand the format of this input. That's where xargs
comes into play.
Moving on to the list of subcommands, here's what they mean:
git branch
: list all local branchesgrep -v "master"
: filter out the word"master"
from the listxargs git branch -D
: delete all branches in the list
Keeping more than 1 branch
Maybe you've got another branch called staging
that you wish to preserve as well. To exclude it from the deletion process, simply add it as follows:
git branch | grep -v "master" | grep -v "staging" | xargs git branch -D