Remove merged git branches

Yes sure everyone usually says “you should remove branches after merges so the repository should be cleaned”, however life is not so easy so many times happened that our repos are full of old branches and no one know if is possible to remove them or not.

First of all all branches should be checked out on local repo on disk, after that git will do the magic.

git branch --merged master lists branches merged into master
git branch --merged lists branches merged into HEAD (i.e. tip of current branch)
git branch --no-merged lists branches that have not been merged

By default this applies to only the local branches. The -a flag will show both local and remote branches, and the -r flag shows only the remote branches.

The script below is very useful to keep your repository cleaned, is easy to copy and paste it on the repository directory and run it as standard bash script.

git push --delete origin $branch
git branch -d $branch

These commands remove respectively remote and local version of the brach. change origin with what you use as “remote_name” if different.

if [ -z "$1" ]; then
        echo "please insert master branch or other merge branch"
        exit 1
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
   git branch --track ${branch#remotes/origin/} $branch
for branch in `git branch --merged master`; do
  if [ "$branch" != "$base_branch" ]; then
    git push --delete origin $branch
    git branch -d $branch

Spread the word. Share this post!

Leave Comment

Your email address will not be published. Required fields are marked *