Skip to content

Instantly share code, notes, and snippets.

@endavid
Last active March 24, 2017 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save endavid/e7f612fbcd54daef578c4a3c8dda8531 to your computer and use it in GitHub Desktop.
Save endavid/e7f612fbcd54daef578c4a3c8dda8531 to your computer and use it in GitHub Desktop.
Remove git merged branches with prompt for every remote branch
function rmb {
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 "Pruning branches no longer on origin..."
git remote prune origin
echo "Fetching merged branches..."
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
if [ -n "$local_branches" ]; then
echo "This will remove the following local branches:"
echo "$local_branches"
read -p "Continue? (y/n): " -n 1 choice
echo
if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
# 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 local branches removed."
fi
fi
if [ -n "$remote_branches" ]; then
echo "Removing remote branches..."
prefix="origin/"
while read -r branch; do
b=${branch#$prefix}
read -p "Delete $branch? (y/n): " -n 1 choice </dev/tty
echo
if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
git push origin --delete "$b"
fi
done <<< "$remote_branches"
fi
fi
}
@endavid
Copy link
Author

endavid commented Mar 24, 2017

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