How to delete all local git branches

If you’re like me, you will quickly end up with a lot of local branches. In an ideal world you would delete the branch after you’re done using it. But real life is different and I quickly end up with 10+ local branches.

In most cases I only need to keep three branches master, devel & stage. To automate this task I have made a bash script that does this one one fell swoop.

First we need to test the command, to make sure we don’t accidentally delete branches we want to keep. Open your terminal and type

git branch | grep -v 'master\|devel\|stage'

Replace master, devel & stage, with the names of the branches you want to keep. This should give you a list of your local branch names, except for the branches you specified in the above command. Note: the above command doesn’t delete any branches.

First command tests that we’re finding the right branches. It doesn’t delete anything.

To delete the branches, add the following to the end | xargs git branch -D

The full command looks like this

git branch | grep -v 'master\|devel\|stage' | xargs git branch -D

Now, that’s a lot to type (and remember), so let’s set up an alias for this.

Open your .bashrc or .zshrc file in your favorite text editor (I’m using vim here) vim ~/.zshrc

Then add the following line

alias gda=”git branch | grep -v ‘master\|devel\|stage’ | xargs git branch -D”

save and quit the fil and type the following in your terminal: source ~/.zshrc or .bashrc if you’re aren’t using http://ohmyz.sh/

Now I can delete all branches I don’t need in one go.