Last active
February 16, 2016 22:34
-
-
Save bpedman/0bd0a04e975f9c57782b to your computer and use it in GitHub Desktop.
Clean up stale local git branches
This file contains hidden or 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 | |
# | |
# Cleans up stale local branches. | |
# | |
# Checks for local branches that used to have a remote branch | |
# but that branch no longer exists. If the branch has no local | |
# changes that have not been merged into a specific branch then | |
# the branch is deleted. | |
# | |
MERGED_BRANCH_TO_CHECK=master | |
git rev-parse --is-inside-work-tree &>/dev/null | |
if [[ $? -ne 0 ]] | |
then | |
echo "Not in a git repository!" | |
exit 1 | |
fi | |
git fetch --prune | |
branches_without_remote=$(git branch -avv | grep gone | sed 's/\*//g' | awk '{ print $1; }') | |
for branch in $branches_without_remote | |
do | |
remote_branches_containing_branch=$(git branch -r --contains $branch | grep $MERGED_BRANCH_TO_CHECK) | |
if [[ -n $remote_branches_containing_branch ]] | |
then | |
git branch -D $branch | |
else | |
echo "Not deleting branch $branch as it has local changes that have not been merged into $MERGED_BRANCH_TO_CHECK" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment