Skip to content

Instantly share code, notes, and snippets.

@mibli
Created June 25, 2021 13:14
Show Gist options
  • Save mibli/ddb58ab0ed52a9c329562907f23193d7 to your computer and use it in GitHub Desktop.
Save mibli/ddb58ab0ed52a9c329562907f23193d7 to your computer and use it in GitHub Desktop.
git cleanup
#!/bin/bash
die() {
echo "$@"
exit 1
}
confirm() {
ans=
while true; do
echo "$@" "[y/n]"
read -r ans
[[ "$ans" =~ ^(y|n)$ ]] && break
done
[ "$ans" = "y" ]
}
[[ "$#" == 0 || "$1" =~ ^(-h|--help)$ ]] && die "Usage: $0 [remote] branch"
if [[ "$#" -gt 2 ]]; then
die "Expected 1 or 2 arguments, got $#"
fi
remote=
if [ "$#" == 2 ]; then
remote="$1"; shift
fi
branch="$1"
if [ -n "$remote" ]; then
git remote | grep -wq "$remote" || die "No such remote $remote"
remote_branch="$remote/$branch"
git branch -r | grep -wq "$remote_branch" || die "Remote branch doesn't exist"
mapfile branches < <(git branch -r --merged "$remote_branch" | sed -e 's/\s*//' -e "/^$remote/!d" -e "/$remote\/\(\*\|$branch\|HEAD\)/d")
else
git branch | grep -wq "$branch" || die "Branch doesn't exist"
mapfile branches < <(git branch --merged "$branch" | sed -e 's/\s*//' -e "/\(\*\|$branch\|HEAD\)/d")
fi
[ "${#branches[@]}" -ne 0 ] || die "No merged branches found"
printf "%s" "${branches[@]}"
confirm "Do You want to remove these branches?" || die "Aborted"
if [ "$#" == 2 ]; then
echo "${branches[@]}" | sed "s_\(^\|\s\)$remote/_\1:_g" | xargs -n1 git push "$remote"
else
echo "${branches[@]}" | xargs git branch -d
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment