Delete all local git branches except main, master, or your current branch.
Let’s take a look at a few different ways of deleting a batch of branches in a git repo.
You can list all git branches except a specific branch using the -v
option in the grep
command. For example, let’s say you wanted to list branches that do not include nodelete
in the name.
git branch | grep -v nodelete
Now, to delete all branches that were returned, pipe to the xargs
command and run git branch -d
.
git branch | grep -v nodelete | xargs git branch -d
This command skips branches that are not fully merged, along with the current branch. It will output a message for every returned branch that it does not delete.
main
For example, to skip the main
branch, you could do this:
git branch | grep -v main | xargs git branch -d
This will skip any branch with main
in its name, even if it’s something like new-domain
.
main
Branch ExactlyThe easiest way to target the main branch is to first check it out, then target the asterisk in the name:
git checkout main
git branch | grep -v "^* main$" | xargs git branch -d
Here, the ^
means "begins with" and $
means "ends with." Therefore, we’re matching exactly * main
, which is how the main branch will be printed when it is checked out.
If you don’t want to worry about checking out a branch, but want to be precise, you can choose to print the branches as a list with no whitespace. Keeping the example of main, here’s what you can do:
git branch --format='%(refname:short)' | grep -v "^main$" | xargs git branch -d
What I really like about using -d
when deleting branches is that it skips branches that are not fully merged. If you want to delete all returned branches, you’ll want to use -D
instead:
git branch | grep -v "..." | xargs git branch -D
Lastly, whether using the -d
or -D
option for deleting branches, you will not be able to delete the current branch. So you can technically just run through the entire list to delete everything except the current branch.
git branch | xargs git branch -d
Notice here that we don’t use the grep
command because there’s nothing to filter from the response.