Script that interactively cleans up remote Git branches already merged into master
#!/usr/bin/env bash | |
# This script will show you all of the branches in the current Git repo that are already | |
# merged into $dest_branch. | |
# | |
# Afterward you will be prompted with whether you want to proceed with deleting those remote | |
# branches (automatically). | |
# | |
# Finally you will be prompted with whether you want to prune local branches. | |
# | |
# Note if you `ln -s` this (or just save it) as `git-delete-merged` you can run it with | |
# `git delete-merged`. | |
# allow passing the destination branch as an argument | |
dest_branch=$1 | |
# default to master if no argument | |
if [ "$dest_branch" == "" ] ; then | |
dest_branch="master" | |
fi | |
prompt_confirm() { | |
while true ; do | |
read -r -p "${1:-Continue?} [y/n]: " reply | |
case $reply in | |
[yY]) return 0 ;; | |
[nN]) return 1 ;; | |
esac | |
done | |
} | |
merged_branches=`git branch -r --merged $dest_branch | egrep -v "upstream\/|master|develop|release\/" | sed 's/origin\///' | xargs -0 -n 1 echo` | |
if [ ! "$merged_branches" == "" ] ; then | |
read -p "Press any key to preview the branches that have already been merged into the $dest_branch branch." | |
echo "$merged_branches" | more | |
prompt_confirm "Do you want to delete above branches?" || exit 0 | |
echo "$merged_branches" | xargs -n 1 git push origin --delete | |
prompt_confirm "Do you want to prune your local branches?" || exit 0 | |
git remote prune origin | |
else | |
echo "There are no outstanding branches merged into $dest_branch - ensure you have the latest changes to $dest_branch by performing a git fetch & pull." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment