Skip to content

Instantly share code, notes, and snippets.

@JamesWatling
Created September 13, 2024 00:03
Show Gist options
  • Save JamesWatling/ef37e683c2f92cb576e90f9848422c06 to your computer and use it in GitHub Desktop.
Save JamesWatling/ef37e683c2f92cb576e90f9848422c06 to your computer and use it in GitHub Desktop.
Delete all local branches more than a month old that don't contain prod/staging/release/main with confirmation
#!/bin/bash
# Function to check branch age and filter out excluded branches
get_old_branches() {
git for-each-ref --sort=-committerdate refs/$1/ \
--format='%(refname:short)' \
| grep -v -E '(prod|staging|release|main)' \
| xargs -n 1 -I {} git log -1 --format="%ci {}" {} \
| awk -v date="$(date -v-30d +%Y-%m-%d)" '$1 <= date {print $4}'
}
# Get local branches older than 30 days
local_branches=$(get_old_branches "heads")
# Get remote branches older than 30 days, stripping the "origin/" prefix
remote_branches=$(get_old_branches "remotes/origin" | sed 's#^origin/##')
# Combine local and remote branches
branches=$(echo -e "$local_branches\n$remote_branches" | sort | uniq)
# Dry run
echo "Dry run - Branches to be deleted locally and remotely:"
echo "$branches"
# Ask for confirmation
read -p "Do you want to delete these branches locally and remotely? (y/n): " confirm
if [ "$confirm" == "y" ]; then
for branch in $branches; do
echo "Branch: $branch"
# Check if the branch exists locally before deleting
if git show-ref --verify --quiet refs/heads/$branch; then
# Delete branch locally
echo "Deleting local branch: $branch"
git branch -D $branch
fi
# Check if the branch exists on the remote and strip "origin/" prefix
if git ls-remote --exit-code --heads origin $branch > /dev/null; then
# Delete branch on remote
echo "Pushing branch deletion to remote: $branch"
git push origin --delete $branch
fi
done
else
echo "Aborted."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment