Skip to content

Instantly share code, notes, and snippets.

@noahduncan
Last active April 17, 2018 14:47
Show Gist options
  • Save noahduncan/72b6e9ec264c485466ac6ea0c35d6829 to your computer and use it in GitHub Desktop.
Save noahduncan/72b6e9ec264c485466ac6ea0c35d6829 to your computer and use it in GitHub Desktop.
Automatic cleanup of merged git branches
function gcleanup ()
{
# default to local cleanup
loc=true
OPTIND=1
while getopts "ahlr" opt; do
case "$opt" in
a) # delete both
rem=true;
loc=true;
;;
h) # Display help
echo -e "\ngcleanup [-rlah] <branch>: Deploys a project.";
echo -e "\nSwitches:";
echo -e "\t-a\t Delete merged branches locally and from the remote.";
echo -e "\t-h\t Display this help message.";
echo -e "\t-l\t (default) Delete merged branches locally.";
echo -e "\t-r\t Delete merged branches from the remote.";
return 0;
;;
l) # delete local
loc=true;
rem=false;
;;
r) # delete remote
rem=true;
loc=false;
;;
esac
done
shift "$((OPTIND-1))"
git checkout master
if [[ $rem == true ]]; then
rbranches=$(git branch -q -r --merged | grep -v '\(master\|HEAD\)');
for branch in $rbranches; do
bn=$(echo $branch | cut -d'/' -f 2-6);
if [ -n "$bn" ]; then
git push origin ":$bn";
fi
done;
fi
if [[ $loc == true ]]; then
lbranches=$(git branch -q --merged | grep -v '\(master\|HEAD\)');
for branch in $lbranches; do
git branch -d $branch;
done;
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment