Last active
February 22, 2026 16:47
-
-
Save gmeligio/ed56d866bbd8e684f163f16d6cbe95d8 to your computer and use it in GitHub Desktop.
git hook to auto clean up merged local branches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1. Create ~/.githooks | |
| # ----------------------------------------------- | |
| mkdir -p ~/.githooks | |
| git config --global core.hooksPath ~/.githooks | |
| # ----------------------------------------------- | |
| # 2. Create ~/.githooks/post-checkout: | |
| # ----------------------------------------------- | |
| cat > ~/.githooks/post-checkout <<'EOF' | |
| #!/usr/bin/env bash | |
| # post-checkout <old-ref> <new-ref> <flag> | |
| # flag=1 for branch checkout, 0 for file checkout | |
| flag="$3" | |
| [ "$flag" = "1" ] || exit 0 | |
| branch="$(git symbolic-ref --quiet --short HEAD 2>/dev/null || true)" | |
| case "$branch" in | |
| main|master) ;; | |
| *) exit 0 ;; | |
| esac | |
| # Only run if gh is available and authenticated | |
| command -v gh >/dev/null 2>&1 || exit 0 | |
| gh auth status >/dev/null 2>&1 || exit 0 | |
| # Ensure we prune remote-tracking refs too | |
| git fetch --prune >/dev/null 2>&1 || true | |
| # Protect common long-lived branches | |
| PROTECTED='^(main|master|develop|dev|staging|release|hotfix)$' | |
| # Delete local branches whose PRs are merged on GitHub | |
| # Notes: | |
| # - headRefName is just the branch name; this assumes your PR head branches are on origin. | |
| # - Limit can be increased; keep modest to avoid slowness. | |
| gh pr list --state merged --limit 100 --json headRefName --jq '.[].headRefName' 2>/dev/null \ | |
| | while read -r br; do | |
| [ -z "$br" ] && continue | |
| echo "$br" | grep -Eq "$PROTECTED" && continue | |
| # Only delete if it exists locally and is not current branch | |
| [ "$br" = "$branch" ] && continue | |
| git show-ref --verify --quiet "refs/heads/$br" || continue | |
| git branch -D "$br" >/dev/null 2>&1 || true | |
| done | |
| exit 0 | |
| EOF | |
| # --------------------------------------------------- | |
| # 3. Make ~/.githooks/post-checkout executable | |
| # --------------------------------------------------- | |
| chmod +x ~/.githooks/post-checkout | |
| # --------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment