Last active
February 13, 2026 12:58
-
-
Save raphaelbs/72dd1dca73f03f1bcb16a31e8914a38f to your computer and use it in GitHub Desktop.
Prune git branches and update default branch
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
| #!/bin/bash | |
| set -euo pipefail | |
| # Verify we're in a git repo | |
| git rev-parse --git-dir > /dev/null 2>&1 || { echo "Not a git repository"; exit 1; } | |
| # Abort if there are uncommitted changes | |
| if ! git diff-index --quiet HEAD -- 2>/dev/null; then | |
| echo "You have uncommitted changes. Stash or commit them first." | |
| exit 1 | |
| fi | |
| # Detect default branch (local, no network call) | |
| BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|refs/remotes/origin/||') | |
| if [ -z "$BRANCH" ]; then | |
| # Fallback: query remote | |
| BRANCH=$(git remote show origin | sed -n '/HEAD branch/s/.*: //p') | |
| fi | |
| # Single fetch that also prunes deleted remote branches | |
| echo "Fetching and pruning..." | |
| git fetch --prune origin | |
| # Switch to default branch and fast-forward | |
| echo "Switching to $BRANCH..." | |
| git checkout "$BRANCH" | |
| git merge --ff-only "origin/$BRANCH" | |
| # Delete local branches whose remote is gone | |
| echo "Deleting merged local branches..." | |
| git branch --format='%(refname:short) %(upstream:track)' \ | |
| | awk '$2 == "[gone]" { print $1 }' \ | |
| | xargs -r git branch -D 2>/dev/null || true | |
| # Garbage collect | |
| echo "Running gc..." | |
| git gc --quiet | |
| echo "Done. Remaining branches:" | |
| git branch --list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Suggestion:
I've added a little change to save the branches list in a file and open it to edition, this way I can exclude branches I don't want to remove now before closing the file.