Skip to content

Instantly share code, notes, and snippets.

@raphaelbs
Last active February 13, 2026 12:58
Show Gist options
  • Select an option

  • Save raphaelbs/72dd1dca73f03f1bcb16a31e8914a38f to your computer and use it in GitHub Desktop.

Select an option

Save raphaelbs/72dd1dca73f03f1bcb16a31e8914a38f to your computer and use it in GitHub Desktop.
Prune git branches and update default branch
#!/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
@LucasMMota
Copy link

LucasMMota commented Oct 7, 2019

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.

#!/bin/bash
echo "Changing branch to master"
git checkout master
echo "Update changes"
git fetch
git pull
echo "Prunning local branches that were removed in remote..."
git remote update --prune
# saves in a file to pre-deletion check
git fetch -p && for branch in `git branch -vv | grep ': gone]' | awk '{print $1}'`; do echo $branch >>/tmp/merged-branches; done 
# (here you can remove branches you don't want to delete)
vi /tmp/merged-branches && xargs git branch -D </tmp/merged-branches
echo "Done"
echo "Listing remaining branches:"
git branch --list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment