Skip to content

Instantly share code, notes, and snippets.

@jrial
Created April 9, 2019 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrial/da28757dc07b4bda6ff40774081d4aa0 to your computer and use it in GitHub Desktop.
Save jrial/da28757dc07b4bda6ff40774081d4aa0 to your computer and use it in GitHub Desktop.
Git tidy: remove tracking branches with no upstream and clean up merged local branches with no tracking branch
#!/usr/bin/env bash
# First, prune the tracking branches without a remote
git fetch --prune
# Now list the ones that have been merged into master
BRANCHES=`git branch -l --merged master|grep -Ev "(^\*| master$| develop$)"`
# Get the SHA of the tip of both master and origin/master for comparison
MASTER_SHA=`git show master --pretty='%H'`
ORIG_MASTER_SHA=`git show origin/master --pretty='%H'`
if [ "${BRANCHES}" == "" ] ; then
echo "There are no branches to tidy up."
if [ "${MASTER_SHA}" != "${ORIG_MASTER_SHA}" ] ; then
echo "But master and origin/master differ, so perhaps you need to"
echo "git pull master?"
fi
else
echo "Found the following branches that have been merged into master and"
echo "that have no remote tracking branch:"
echo
for branch in ${BRANCHES} ; do
echo " ${branch}"
done
echo
# Print the branches, ask for confirmation before deleting.
read -p "Delete these? (y/N) " PERMISSION_TO_DELETE
# Finally, delete. If allowed.
if [[ "${PERMISSION_TO_DELETE}" == "Y" || "${PERMISSION_TO_DELETE}" == "y" ]] ; then
echo "OK, deleting..."
for branch in ${BRANCHES} ; do
git branch -r |grep "${branch}" || git branch -d "${branch}"
done
fi
fi
@jrial
Copy link
Author

jrial commented Apr 9, 2019

This script will first remove all tracking branches that no longer have an upstream by calling git fetch --prune.

Then it will check if there are local branches that are merged into master, excluding develop and master itself, print them to the screen and offer to delete them.

To install: put this file somewhere in your $PATH, and make it executable. If you name it git-tidy, as I did, you can call it with: git tidy. Before calling it, checkout master and pull. The script doesn't do that since that would change your current branch and contents of your working folder, which should be a deliberate action and not a side effect of running a script.

This is a logical continuation of the standalone script at https://gist.github.com/jrial/97f77fcafe6d9733c7d6f7d7df37e4a1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment