Skip to content

Instantly share code, notes, and snippets.

@sparrc
Last active March 10, 2022 22:36
Show Gist options
  • Save sparrc/8aaf5ad1d63097fbef77da5b4ed630b1 to your computer and use it in GitHub Desktop.
Save sparrc/8aaf5ad1d63097fbef77da5b4ed630b1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# if the most recent commit on the branch is older than MAX_AGE_DAYS, then the branch
# will be deleted.
MAX_AGE_DAYS=180
# if DRY_RUN=1, then only print the names of the branches that would be deleted.
if [ -z "$DRY_RUN" ]; then
DRY_RUN=0
fi
startbranch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch -a); do
if echo $branch | grep "remotes/origin" &>/dev/null; then
continue
fi
# protected branches
if [[ $branch == "master" ]]; then continue; fi
if [[ $branch == "mainline" ]]; then continue; fi
if [[ $branch == "main" ]]; then continue; fi
if [[ $branch == "dev" ]]; then continue; fi
if [[ $branch == "HEAD" ]]; then continue; fi
if ! git checkout $branch &>/dev/null; then continue; fi
if (($(git log -1 --format=%ct) < $(date -d "-$MAX_AGE_DAYS days" +%s))); then
if [ $DRY_RUN -ne 0 ]; then
echo "dry run: would delete branch $branch"
else
git checkout $startbranch
git branch -D $branch
fi
fi
done
git checkout $startbranch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment