Last Updated: February 25, 2016
·
6.252K
· jfeldstein

Bash script to clean up obsolete git branches

Run this to clean up obsolete branches from local and remote (origin) at once.

Put this script in a file in ~/bin/, and run chmod +x ~/bin/scriptname. Restart your terminal and run the script.

Thanks to http://devblog.springest.com/a-script-to-remove-old-git-branches

Known problems:
- If you have other remotes besides "origin" it gets noisy (but still works)
- If you're main remote is not called "origin" you'll need to edit the script accordingly.

# This has to be run from master

git checkout master

# Update our list of remotes

git fetch
git remote prune origin

# Remove local fully merged branches

git branch --merged master | grep -v 'master$' | xargs git branch -d

# Show remote fully merged branches

echo "The following remote branches are fully merged and will be removed:"
git branch -r --merged master | sed 's/ *origin\///' | grep -v 'master$'

read -p "Continue (y/n)? "
if [ "$REPLY" == "y" ]
then
   # Remove remote fully merged branches
   git branch -r --merged master | sed 's/ *origin\///' \
             | grep -v 'master$' | xargs -I% git push origin :%
   echo "Done!"
fi