Skip to content

Instantly share code, notes, and snippets.

@raphaelbs
Last active March 7, 2024 17:41
Show Gist options
  • Save raphaelbs/72dd1dca73f03f1bcb16a31e8914a38f to your computer and use it in GitHub Desktop.
Save raphaelbs/72dd1dca73f03f1bcb16a31e8914a38f to your computer and use it in GitHub Desktop.
Prune git branches and update default branch
#!/bin/bash
BRANCH=$(git remote show origin | sed -n '/HEAD branch/s/.*: //p')
echo "Update changes"
git fetch -u origin $BRANCH:$BRANCH
git pull --ff-only origin $BRANCH:$BRANCH
echo "Changing branch to $BRANCH"
git checkout $BRANCH
echo "Prunning local branches that were removed in remote..."
git remote update --prune
git fetch -p && for branch in `git branch -vv | grep ': gone]' | awk '{print $1}'`; do git branch -D $branch; done
echo "Git GCing"
git gc
git prune
echo "Done"
echo "Listing 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