Tiny tips: Git – Delete all local branches

This is one of the “Tiny tips” series.
The purpose is to share little pieces of helpful practices and tricks that will make your work better and more pleasant.

Take a look at the other tiny tips like Automate your environment, Use cheat sheets, Git merge without commit

Perhaps most of you are working on a project where for each story, you create a corresponding GitHub branch.
Also, for each code review of another person’s implementation, you must clone the corresponding branch of your colleague.
In this way, if you do not maintain good discipline, you will find yourself in a short time with many local branches.
If you are using Visual Studio, you will see a long list of local branches in the Git Changes tab. If you decide to delete the unnecessary ones through the Visual Studio interface, it offers you the possibility to delete them one by one.

So, a git command for batch delete would be useful, right?

Here’s what I use:

git branch | grep -v "This-Branch-Will-Stay" | xargs git branch -D

Here is a description of the command’s elements:

  • git branch:

“The git branch command lets you create, list, rename, and delete branches.” (https://www.atlassian.com/git/tutorials/using-branches)

  • grep -v “This-Branch-Will-Stay”:

“Git ships with a command called grep that allows you to easily search through any committed tree, the working directory, or even the index for a string or regular expression.” (https://git-scm.com/book/en/v2/Git-Tools-Searching)
-v is a switch that changes the command so that it filters out lines that contain the pattern instead of printing lines that match the pattern. So in this case, “This-Branch-Will-Stay” would be the name of a Git branch that you want to keep. The command then prints the names of all branches except “This-Branch-Will-Stay”.

  • xargs git branch -D:

xargs is a command that converts files names, keyboard input, and outputs into arguments to a utility or function. xargs here runs the git branch -D command on each (in this case) branch name. The -D flag tells git to delete the branch regardless of its status.

Leave a comment