Created
May 31, 2012 14:08
-
-
Save zrzka/2843623 to your computer and use it in GitHub Desktop.
Git - prune remote origin and delete local branches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Written by Robert Vojta <robert@tapmates.com> | |
# | |
# This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. | |
# | |
# http://creativecommons.org/licenses/by-sa/3.0/ | |
# | |
# | |
# What it does ... | |
# | |
# - gets list of local branches (master and current branch is skipped) | |
# - gets list of remote branches (master, HEAD are skipped) | |
# - if local branch doesn't exist in remote branches list, it will be deleted | |
# | |
# ... that's all. Simple, but be aware, your local branches are going to be deleted! | |
# | |
OIFS="$IFS" | |
IFS=$(echo -en "\n\b" ) | |
# | |
# Prune remotes | |
# | |
echo -ne "Fetching changes ... " | |
git fetch &> /dev/null | |
echo -ne "done\nPruning remote origin ... " | |
git remote prune origin &> /dev/null | |
echo "done" | |
# | |
# List of branches | |
# | |
trim() { echo $1 | sed 's/^ *//g' | sed 's/ *$//g'; } | |
echo -e "\nLocal branches" | |
declare -a LBRANCHES | |
for line in $( git branch -l | grep -v \* ); do | |
BRANCH=$(trim $line) | |
if [ "$BRANCH" != "master" ]; then | |
LBRANCHES=("${LBRANCHES[@]}" "$BRANCH") | |
echo " $BRANCH" | |
fi | |
done | |
if [ ${#LBRANCHES[@]} -eq 0 ] ; then | |
echo -e "\nNo local branches, nothing to do" | |
IFS="$OIFS" | |
exit 0 | |
fi | |
echo -e "\nRemote branches" | |
declare -a RBRANCHES | |
for line in $( git branch -r | grep -v \* ); do | |
BRANCH=$(trim ${line/origin\//}) | |
if [[ ! "$BRANCH" =~ HEAD|master ]]; then | |
RBRANCHES["$BRANCH"]=1 | |
echo " $BRANCH" | |
fi | |
done | |
# | |
# Get local branches to delete | |
# | |
declare -a DBRANCHES | |
for BRANCH in "${LBRANCHES[@]}"; do | |
if [[ ! ${RBRANCHES["$BRANCH"]} ]]; then | |
DBRANCHES=("${DBRANCHES[@]}" "$BRANCH") | |
fi | |
done | |
if [ ${#DBRANCHES[@]} -eq 0 ] ; then | |
echo -e "\nNo local branches to delete, nothing to do" | |
IFS="$OIFS" | |
exit 0 | |
fi | |
echo -e "\nList of local branches to delete" | |
for BRANCH in "${DBRANCHES[@]}"; do | |
echo " $BRANCH" | |
done | |
echo -e "\nBranches listed above will be deleted! There's no way to go back!" | |
echo -en "\nProceed? (Y/n):" | |
read proceed | |
if [ "$proceed" == "Y" ]; then | |
for BRANCH in "${DBRANCHES[@]}"; do | |
echo -en "\nDeleting branch $BRANCH ... " | |
git branch -D "$BRANCH" &> /dev/null | |
if [[ $? -eq 0 ]]; then | |
echo "done" | |
else | |
echo "failed" | |
fi | |
done | |
fi | |
IFS="$OIFS" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment