When working on a big project, particularly something that is in production, you end up constantly creating new branches for features and bug fixes.

At some point, your local repository gets really messy, full of stale and remote deleted branches.

You can manage this by deleting branches individually. For example, you can run the following command:

git branch -D <branch_name>

Yes, this will work. However, running this command for every local branch can be really time-consuming, particularly if you have not deleted any branches for a long time. Have fun doing this for tens or hundreds of branches.

Wouldn’t it be great if you could quickly delete all of these branches while keeping master? There is!

git branch | grep -v "master" | xargs git branch -D

This lovely piece of code will delete every local git branch except master. Awesome!

However, this command is a real pain to remember. Chances are you will have to keep looking this up and copy/paste it. That sucks!

Let’s make it quicker and easier using a bash alias.

Delete All Git Branches Using a Bash Alias

Open your .bashrc file, which should be located in your root directory. Paste in the following bash alias.

alias gda='git branch | grep -v "master" | xargs git branch -D'

Now all you have to do is type gda into your bash terminal and you can delete all of those old git branches. After running the command you should see something like the following:

Deleted branch branch1 (was ez633e2).
Deleted branch branch2 (was 9vde961).
Deleted branch branch3 (was 7a8cb89).
Deleted branch branch4 (was d5azc39).

gda stands for “git delete all“, so it should be really easy to remember.

And there you have it! With this bash alias, keeping your local git repository nice and clean should never be a problem again.

I hope this guide was helpful. If you want to read more cool bash alias content, I wrote an article showcasing 3 Ways To Disable a Bash Alias. Sometimes an alias can get in the way of other commands, so if you want to know how to disable a bash alias, check it out.

Thanks for reading! Keep having fun with git and bash aliases!