Skip to content

Instantly share code, notes, and snippets.

@pfrenssen
Last active September 22, 2017 10:02
Show Gist options
  • Save pfrenssen/8859546 to your computer and use it in GitHub Desktop.
Save pfrenssen/8859546 to your computer and use it in GitHub Desktop.
Checks the available git branches and deletes all branches that are fully merged in the main branch.
#!/bin/bash -e
# Checks the available git branches and deletes all branches that are fully
# merged in the main branch.
#
# Source: http://devblog.springest.com/a-script-to-remove-old-git-branches
# Configuration
if [ -z ${MAIN_BRANCH} ]; then
MAIN_BRANCH=develop
fi
if [ -z ${REMOTE} ]; then
REMOTE=origin
fi
# Run this from the main branch.
git checkout "${MAIN_BRANCH}"
# Update our list of remotes.
git fetch
git remote prune ${REMOTE}
# Remove local fully merged branches, except the main branch and any detached branches.
git branch --merged "${REMOTE}/${MAIN_BRANCH}" | grep -v "^[( |*)] ${MAIN_BRANCH}$" | grep -v "(HEAD detached at [0-9a-f]*)" | xargs --no-run-if-empty git branch -d
# Show remote fully merged branches.
echo "The following remote branches are fully merged and will be removed:"
MERGED_BRANCHES=$(git branch -r --merged "${REMOTE}/${MAIN_BRANCH}" | grep "^ ${REMOTE}\/" | sed "s/ ${REMOTE}\///" | grep -v "^${MAIN_BRANCH}$" | grep -v "^master$")
echo "$MERGED_BRANCHES"
read -p "Continue (y/n)? "
if [ "${REPLY}" == "y" ]
then
# Remove remote fully merged branches.
echo "$MERGED_BRANCHES" | xargs --no-run-if-empty -I% git push ${REMOTE} :%
echo "Done!"
echo "Obsolete branches are removed"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment