Skip to content

Instantly share code, notes, and snippets.

@terrafied
Created January 15, 2012 21:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrafied/1617395 to your computer and use it in GitHub Desktop.
Save terrafied/1617395 to your computer and use it in GitHub Desktop.
Remove merged branches from a git repo
#!/bin/bash
# From: http://snippets.freerobby.com/post/491644841/remove-merged-branches-in-git
current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo "Fetching merged branches..."
git remote prune origin
remote_branches=$(git branch -r --merged | grep -v '/master$' | grep -v "/$current_branch$")
local_branches=$(git branch --merged | grep -v 'master$' | grep -v "$current_branch$")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
echo "No existing branches have been merged into $current_branch."
else
echo "This will remove the following branches:"
if [ -n "$remote_branches" ]; then
echo "$remote_branches"
fi
if [ -n "$local_branches" ]; then
echo "$local_branches"
fi
read -p "Continue? (y/n): " -n 1 choice
echo
if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
# Remove remote branches
git push origin `git branch -r --merged | grep -v '/master$' | grep -v "/$current_branch$" | sed 's/origin\//:/g' | tr -d '\n'`
# Remove local branches
git branch -d `git branch --merged | grep -v 'master$' | grep -v "$current_branch$" | sed 's/origin\///g' | tr -d '\n'`
else
echo "No branches removed."
fi
fi
@wajiii
Copy link

wajiii commented Feb 22, 2012

This raises a philosophical question for me; I hate to throw away history, and it's fun to look back at GitHub's network graph for the repo, but OTOH, in an average day the long list of branches can get annoying. What to do?! I wish there were just a way to hide merged branches by default in 'git branch' and the GitHub drop-down list, and only show them if specifically requested.

@terrafied
Copy link
Author

Screw that! Delete em. The history of the branch is pulled into the master branch when it's merged. That's why the rebase workflow is nice. Am I wrong about that?

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