Loading...

Clean Already Merged Branches in Git

Productivity
September 8, 2019
2 minutes to read
Share this post:

Another month, another git alias (But don’t think that this will become a regularity now ;-) ). I had the issue that I lost track of the branches that were already in master a couple of times on one of my projects and after a while I had a lot of unnecessary jobs in Jenkins because we use the Jenkins multibranch plugin . So I sat down and created a git alias that does the cleanup for you with a bit of user-friendly output.

The strategy is pretty simple. We can figure out which branches are already merged into master by executing:

git branch --merged master

As we want to filter out the branch we are currently on (because we aren’t able to delete it anyway) and the master branch itself we pipe it through egrep:

git branch --merged master | egrep -v "(^\*|master)"

For the resulting list we simply need to execute git branch -d to delete the branches locally and git push --delete origin to delete them on remote as well.

With some additional user feedback and safety nets we and up with a script like this:

#!/bin/bash

BRANCHES=$(git branch --merged master | egrep -v "(^\*|master)")
if [ -z "$BRANCHES" ]; then
  echo "Found no branch to delete"
  exit
fi

function delete_branches() {
    echo $BRANCHES | xargs git branch -d
}

function delete_remote_branches() {
    echo $BRANCHES | xargs git push --delete origin
    git remote prune origin
}

echo "Are you sure you want to delete these branches?"
echo $BRANCHES | tr " " "\n"
printf "\n"

select yn in "Yes" "No"; do
    case $yn in
        Yes ) delete_branches; break;;
        No ) exit;;
    esac
done

echo "Do you also want to delete the remote tracking branches?"

select yn in "Yes" "No"; do
    case $yn in
        Yes ) delete_remote_branches; break;;
        No ) exit;;
    esac
done

At last, we also want to use it as a git alias, so we add it with:

git config --global alias.clean-merged "! PATH/TO/YOUR/SCRIPT"

#usage:
git clean-merged

Have you heard of Marcus' Backend Newsletter?

New ideas. Twice a week!
Top