Skip to content

Instantly share code, notes, and snippets.

@ohnit
Created February 25, 2020 18:18
Show Gist options
  • Save ohnit/c0a621725a1370929bfc9f675e7e75f1 to your computer and use it in GitHub Desktop.
Save ohnit/c0a621725a1370929bfc9f675e7e75f1 to your computer and use it in GitHub Desktop.
Delete local git branches that have been merged
#! /bin/bash
# deletes branches (other than `master` or `develop`) that have already been merged into your
# current branch. I prefer this: https://gist.github.com/ohnit/150cb10459328e4695956567da5840b8
confirm() {
# 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() {
# branches merged into the current branch (exclude master and develop)
git branch --merged | grep -v '* \|master\|develop'
# Deletes based on upstream branch deletion instead of merge
# git branch -vv | awk '/: gone]/{print $1}'
}
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
if [ "$branch_name" != "master" ] && [ "$branch_name" != "develop" ]
then
echo "You are not on master or develop!!!"
echo "You are on this branch: $branch_name"
confirm "Are you sure you want to continue? [y/N]" || exit 0
fi
echo
echo "This will delete the follow branches..."
merged_branches | xargs -I % echo " %"
echo
confirm "Would you like to continue? [y/N]"
if [ $? -ne 0 ]
then
echo "aborted"
exit 1
fi
merged_branches | xargs git branch -d
echo
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment