Skip to content

Instantly share code, notes, and snippets.

@jaredhabeck
Created November 3, 2015 16:48
Show Gist options
  • Save jaredhabeck/7a6262d3c7258dd271ab to your computer and use it in GitHub Desktop.
Save jaredhabeck/7a6262d3c7258dd271ab to your computer and use it in GitHub Desktop.
A bash script to clean up remote branches that pile up. Use '-r <remote>' to specify a remote such as 'origin'.
#!/bin/bash
_check_options() {
while test $# -gt 0; do
case "$1" in
-h|--help)
echo "options:"
echo "-h, --help show brief help"
echo "-r, --remote=ORIGIN remote repository to target"
exit 0
;;
-o)
shift
if test $# -gt 0; then
remote=$1
if [[ $(git remote | grep $1 -c) -eq 0 ]]; then
echo "Remote repository not found."
exit 1
fi
else
echo "No remote repository specified."
exit 1
fi
shift
;;
*)
break
;;
esac
done
}
# default remote to 'origin'
remote='origin'
_check_options $@
read -p "Checking out master, and performing a pull to obtain current HEAD. Continue? [Y/n]" prompt
if [[ $prompt == "n" ]]; then
echo 'Exiting.'
exit
fi
git checkout master && git pull > /dev/null 2>&1
if [[ $? -eq 0 ]]; then
# get merged remotes, ignore master!
branches=$(git branch -r --merged $remote | grep -v 'master')
branches_cleaned=0
for branch in $branches ; do
# necessary because remote delete wants branch name only!
base_branch=$(basename $branch)
last_edit=$(git log -1 --format=%cd $branch)
echo
echo "Branch: $base_branch"
echo "Last commit: $last_edit"
echo "Delete? [Y/n/a]"
read prompt
if [[ $prompt == "n" ]]; then
continue
elif [[ $prompt == "a" ]]; then
echo 'Exiting.'
exit
else
((branches_cleaned++))
echo
echo "Deleting $base_branch"
echo
git push $remote :$base_branch
if [[ $? -ne 0 ]]; then
echo "Error deleting remote branch, exiting."
exit 1
fi
fi
done
if [[ $branches_cleaned -gt 0 ]]; then
echo "$branches_cleaned Branches cleaned."
read -p "Prune remote: $remote? [Y/n]" prompt
if [[ $prompt == "n" ]]; then
echo 'Exiting.'
exit
else
git remote prune $remote
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment