Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prune local and remote merged branches
#!env bash
# NOTE: based on
# https://coderwall.com/p/fkk2lw/bash-script-to-clean-up-obsolete-git-branches
# Changes made to first only remove branches you've checked out,
# then 2nd repo-wide check.
# also added human-readable output and prompts
# This has to be run from master
git checkout master
# Update our list of remotes
git fetch
# Prune references to non-existend remote-tracking braches
git remote prune origin
FILTER='^\(master\|HEAD\|release\|develop\|feature\)'
LOCALS=`git branch --merged | sed -E "s/\*? *//" | grep -v "$FILTER"`
REMOTES=`git branch -r --merged | sed -E "s/ *origin\///" | grep -v "$FILTER"`
if [[ "$LOCALS" != "" ]]; then
# Show local fully merged branches
echo "
$LOCALS
---
The above LOCAL branches are fully merged and will be removed,
along with their REMOTE counterparts.
---"
read -p "Continue (yes/n)? "
if [ "$REPLY" == "yes" ]; then
# Remove remote fully merged branches
echo "$LOCALS" | xargs git br -d
echo "$LOCALS" | xargs -I% git push origin :%
echo "LOCAL branches removed!"
fi
fi
if [[ "$REMOTES" != "" ]]; then
# Show remote fully merged branches
echo "
$REMOTES
---
The above REMOTE branches are fully merged and will be removed.
---"
read -p "Continue (yes/n)? "
if [ "$REPLY" == "yes" ]; then
# Remove remote fully merged branches
echo "$REMOTES" | xargs -I% git push origin :%
echo "REMOTE branches removed!"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.