Last active
March 10, 2022 22:36
-
-
Save sparrc/afbae26ee7be2394f23db54fc0e2dbb2 to your computer and use it in GitHub Desktop.
Delete old remote branches in git using `git push --delete origin`
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
#!/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 | |
for branch in $(git branch -a); do | |
if echo $branch | grep "remotes/origin" &>/dev/null; then | |
b=$(echo $branch | sed 's/remotes\/origin\///g') | |
else | |
continue | |
fi | |
# protected branches | |
if [[ $b == "master" ]]; then continue; fi | |
if [[ $b == "mainline" ]]; then continue; fi | |
if [[ $b == "main" ]]; then continue; fi | |
if [[ $b == "dev" ]]; then continue; fi | |
if [[ $b == "HEAD" ]]; then continue; fi | |
# skip branch if there is some problem checking it out | |
if ! git checkout $b &>/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 $b" | |
else | |
git push --delete origin $b | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment