Skip to content

Instantly share code, notes, and snippets.

@bpedman
Last active February 16, 2016 22:34
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 bpedman/0bd0a04e975f9c57782b to your computer and use it in GitHub Desktop.
Save bpedman/0bd0a04e975f9c57782b to your computer and use it in GitHub Desktop.
Clean up stale local git branches
#!/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