Skip to content

Instantly share code, notes, and snippets.

@richmondwang
Last active July 13, 2016 03:51
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 richmondwang/61abbd8db51a2da1dcfa to your computer and use it in GitHub Desktop.
Save richmondwang/61abbd8db51a2da1dcfa to your computer and use it in GitHub Desktop.
This will 'delete' (git branch -D) all branches containing a substring (prefix) that are already merged to origin/master
#!/bin/sh
# Created by richmondwang
# Required: bash4, git1.7, sed, awk, grep
#
# This will 'delete' (git branch -dl) all branches
# containing a substring (prefix) that are already merged to origin/master
prefix="feature/richmond/"
# only delete my own branches
if [ "$1" != "" ]; then
prefix=$1
# or specify a prefix as argument
fi
currentBranch=$(git branch | grep "*" | awk '{print $2;}')
git checkout master
IFS=" " read -r -a branches <<< $(git branch -r --no-merged | grep ${prefix} | sed 's/\// /' | awk '{print $2;}' | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g')
# get all existing branches in remote
localBranches=$(git branch | grep ${prefix} | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n / /g')
# get all local branches
deleted=$localBranches
for branch in ${branches[@]}; do
# loop and delete one by one
deleted=$(sed "s!${branch}!!" <<< ${deleted})
done
if [ "$deleted" == "" ]; then
echo "Nothing to delete, you local is clean."
else
git branch -dl ${deleted}
fi
git checkout $currentBranch
# checkout where you last checked out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment