Skip to content

Instantly share code, notes, and snippets.

@llvtt
Created August 15, 2018 16:56
Show Gist options
  • Select an option

  • Save llvtt/18ad7b130841ebba533d57a9ff5a0146 to your computer and use it in GitHub Desktop.

Select an option

Save llvtt/18ad7b130841ebba533d57a9ff5a0146 to your computer and use it in GitHub Desktop.
Clean up orphaned git branches
#!/bin/bash
if [ "$1" = "rm" ]; then
branches_file=${2:-"orphaned-branches.txt"}
echo "Removing branches specified in $branches_file"
while read branch; do
git branch -D $branch
done < $branches_file
exit 0
fi
tmpdir=`mktemp -d`
git ls-remote --refs --heads | awk '{print $2}' | sed 's/refs\/heads\///' | while read branch; do
mkdir -p "${tmpdir}/${branch}"
done
rm -f orphaned-branches.txt
git branch | sed 's/\* //' | while read branch; do
[ ! -d "${tmpdir}/${branch}" ] && echo $branch >> orphaned-branches.txt
done
rm -rf $tmpdir
cat orphaned-branches.txt
echo "---------------------------------------------------------------"
echo "Orphaned branches written to orphaned-branches.txt"
echo "Edit this file to contain only branches you want to remove,"
echo "then rerun $0 with the 'rm' argument to delete them"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment