Skip to content

Instantly share code, notes, and snippets.

@dreki
Created February 14, 2023 19:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreki/e9f792ecd3609782c5427980a4ba3c77 to your computer and use it in GitHub Desktop.
Save dreki/e9f792ecd3609782c5427980a4ba3c77 to your computer and use it in GitHub Desktop.
Delete git branches that have been merge to `master` via PR.
#!/usr/bin/env bash
# For all local git branches in the current directory, check if they have a merged PR. If so, offer to delete the branch and the remote. If not, print the PR number and URL.
# Usage: git-delete-merged-branches
# Requires: git, gh, jq
set -e
bold=$(tput bold)
normal=$(tput sgr0)
# Get all local branches
branches=$(git branch --format='%(refname:short)')
# Loop through each branch
for branch in $branches; do
# Skip master branch
if [ "$branch" = "master" ]; then
continue
fi
# Print blank line
echo
# Get the PR number for the branch. Ensure it's closed.
pr=$(gh pr list --search "is:closed base:master head:$branch" --json number,url --jq '.[0].number')
# If the PR number is empty, the branch has no merged PR
if [ -z "$pr" ]; then
echo "No merged PR for branch $branch. Skipping."
continue
fi
# Print that the branch has a merged PR, in bold.
echo -e "${bold}Branch $branch has merged PR #$pr${normal}"
# echo -e "\e[1mBranch $branch has merged PR $pr\e[0m"
# Ask if the user wants to delete the branch and the remote
read -p "Delete branch $branch and remote? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
# Delete the branch and the remote
git push origin --delete "$branch"
git branch -D "$branch"
fi
done
echo "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment