bin/git-prune-branches
#!/usr/bin/env bash
#
# git-prune-branches
#
# Simple script that cleans up unnecessary branches.
#
# First it deletes each fully merged branch after prompting
# for confirmation.
#
# Then it prunes all branches that no longer exist at each upstream
# remote.
#
# Author: Michael Demmer https://github.com/demmer
# License: MIT
# Original source: https://github.com/jut-io/git-scripts/blob/master/bin/git-prune-branches
PRIMARY_BRANCH=$(git remote show origin | awk '/HEAD branch/ {print $3}')
if [[ -z "$PRIMARY_BRANCH" ]]; then
echo "Could not determine primary branch"
exit 13
fi
merged=$(git branch --no-color --merged "$PRIMARY_BRANCH" | grep -v "$PRIMARY_BRANCH" | sed 's/\*/ /')
if [ -n "$merged" ] ; then
echo "Deleting the following merged branches:"
for branch in $merged ; do
echo " " "$branch"
done
all=n
delete=n
for branch in $merged ; do
if [ $all = 'n' ] ; then
delete=n
# shellcheck disable=SC2162
read -p "Delete $branch (y=yes, n=no, a=all)? " prompt
echo "all=$all delete=$delete prompt=$prompt"
if [ "$prompt" = 'a' ] ; then
delete=y
all=y
elif [ "$prompt" = 'y' ]; then
delete=y
fi
fi
if [ "$delete" = 'y' ] ; then
git branch -d "$branch"
fi
done
fi
remotes=$(git remote)
for remote in $remotes ; do
prompt=n
# shellcheck disable=SC2162
read -p "Prune deleted branches from remote '$remote' (y=yes n=no)? " prompt
if [ "$prompt" = 'y' ] ; then
git remote prune "$remote"
fi
done