With  our git workflow we often have a lot of unused, old feature branches. These branches don’t do real harm. They’re just sitting there, gathering dust and cluttering our branch list.

It’s easy to forget to remove a feature branch after merging. So we have to remove these branches afterwards. We have  blogged about this process before. The commands described there work, but the process of identifying and removing these branches one by one is boring and cumbersome. I didn’t feel like doing this manually, so I created a script to do this.

Our starting point is git branch –merged master. This will list all branches which have been merged in master:$ git branch –merged master 2034_disablevalidation

  • master It turns out that, right now, only the branch 2034_disablevalidation has been fully merged in master. We can remove this branch safely without losing a single commit. Let’s filter out that master branch and pipe it to the branch delete command:

git branch –merged master | grep -v ‘master$’ | xargs git branch -d There, we removed all obsolete branches from our local repository. Now we continue with the remote branches:

$ git branch -r –merged master origin/1981_usersnotifications origin/2034_disablevalidation origin/HEAD -> origin/master origin/master At the origin, there are two branches to be removed. We remove the origin/ from each line with sed. Filter out the master and head with grep. Then use git push origin :branchname to remove the remote branch:

git branch -r –merged master | sed ‘s/ *origin\///’ | grep -v ‘master$’ | xargs -I% git push origin :% These two commands will remove all obsolete branches, both locally and remote. They will never throw away any commits which are not already merged in master. This means they’re always reversible using git-log and git-checkout. For completeness, here’s the full script:

This has to be run from master

git checkout master

Update our list of remotes

git fetch git remote prune origin

Remove local fully merged branches

git branch –merged master | grep -v ‘master$’ | xargs git branch -d

Show remote fully merged branches

echo “The following remote branches are fully merged into master and will be removed:” git branch -r –merged master | sed ‘s/ *origin\///’ | grep -v ‘master$’

read -p “Continue (y/n)? “ if [ “$REPLY” == “y” ] then # Remove remote fully merged branches git branch -r –merged master | sed ‘s/ *origin\///’ | grep -v ‘master$’ | xargs -I% git push origin :% echo “Done!” say “Obsolete branches are removed” fi