Created
May 4, 2018 12:37
-
-
Save jrial/97f77fcafe6d9733c7d6f7d7df37e4a1 to your computer and use it in GitHub Desktop.
Bash script for deleting local and remote branches that have been merged into master
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
BRANCHES_BEFORE_LOCAL=`git branch -l|wc -l` | |
BRANCHES_BEFORE_REMOTE=`git branch -r|wc -l` | |
# Check if we need to pop our changes afterwards | |
if [ "`git stash save`" == "No local changes to save" ] ; then | |
POP_CHANGES="false" | |
else | |
POP_CHANGES="true" | |
fi | |
git checkout master && \ | |
git fetch --all --prune && git pull && \ | |
for branch in `git branch |grep -v master|grep -v develop` ; do | |
git branch --contains ${branch} | grep '* master' > /dev/null && \ | |
git branch -d ${branch} ; \ | |
done | |
for branch in `git branch -r|grep -v master |grep -v develop` ; do | |
git branch --contains ${branch} | grep '* master' > /dev/null && \ | |
git push origin :`echo ${branch}|sed -e 's#origin/##'` ; \ | |
done | |
git checkout - | |
if [ "$POP_CHANGES" == "true" ] ; then | |
git stash pop | |
fi | |
BRANCHES_AFTER_LOCAL=`git branch -l|wc -l` | |
BRANCHES_AFTER_REMOTE=`git branch -r|wc -l` | |
echo | |
echo "Cleanup finished." | |
echo "Local branches remaining: ${BRANCHES_AFTER_LOCAL}/${BRANCHES_BEFORE_LOCAL}" | |
echo "Remote branches remaining: ${BRANCHES_AFTER_REMOTE}/${BRANCHES_BEFORE_REMOTE}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I created this script to make our branch list a bit more manageable. We often forget to delete our merged branches, both locally and remotely, which makes it harder to find the name of that active branch your colleague was working on. This script attempts to remedy that by pruning all branches that have been deleted upstream, and deleting all local and remote branches that have been merged into master, both locally and upstream.
This doesn't address abandoned branches that have never been merged.
For a git command that does more or less the same thing, see https://gist.github.com/jrial/da28757dc07b4bda6ff40774081d4aa0#gistcomment-2884328