2 minutes

How to Delete all Local Branches in Git?

By Nilanchala @nilan, On Sep 17, 2023 Git 2.61K Views

When working with a larger team and with a proper Git flow process, the number of local feature branches are grows in your local machine. Not that they do any harm to your project, but they can get quite confusing at times. This little code snippet will be able to delete all other local branches except master, develop or release/*.

Create a file named, and add the following code snippet.

# Move to master branch. Delete all other local branches except master, develop, release/* or project/*

# Move to master branch
git checkout master

# Collect branches
eval "$(git for-each-ref --shell --format='branches+=(%(refname))' refs/heads/)"

for branch in "${branches[@]}"; do
  if [[ "$branchName" != "master" && "$branchName" != "develop" &&  "$branchName" != "release/"* ]]; then
    git branch -D $branchName

Now run the shell script

$ ./
nilan avtar


I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.