Skip to content

Instantly share code, notes, and snippets.

@ohnit
Last active September 14, 2022 14:18
Show Gist options
  • Save ohnit/150cb10459328e4695956567da5840b8 to your computer and use it in GitHub Desktop.
Save ohnit/150cb10459328e4695956567da5840b8 to your computer and use it in GitHub Desktop.
Clean up local git branches that have been deleted on remote
#! /bin/bash
# deletes local branches that have been deleted on remote
# this version requires that `git fetch -p` is used to prune remote branches from your local repo
declare force
force=false
if [ $# -gt 0 ]; then
case "$1" in
--force|-D)
force=true;;
*)
echo "Unknown argument"
exit 1;;
esac
fi
confirm()
{
local response
# call with a prompt string or use a default
read -r -p "${1:-Are you sure? [y/N]} " response
case "${response}" in
[yY][eE][sS]|[yY])
true;;
*)
false;;
esac
}
merged_branches()
{
# Deletes based on upstream branch deletion instead of actual merges
git branch -vv | awk '!/^\*/ && /: gone]/ { print $1 }'
}
declare -a merged
# shellcheck disable=SC2207
merged=($(merged_branches))
if (( !${#merged[@]} )); then
echo "No merged branches to delete."
exit 0
fi
echo "This will delete the follow branches..."
for branch in "${merged[@]}"; do
echo " ${branch}"
done
echo
if ! confirm "Would you like to continue? [y/N]"; then
echo "aborted"
exit 1
fi
if $force; then
git branch -D "${merged[@]}"
else
git branch -d "${merged[@]}"
fi
echo
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment